asp.net后台发送HTTP请求
一、文件流方式(转自:http://blog.csdn.net/u011511086/article/details/53216330)
/// 发送请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="sendData">参数格式 “name=王武&pass=123456”</param>
/// <returns></returns>
public static string RequestWebAPI(string url, string sendData)
{
string backMsg = "";
try
{
System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
httpRquest.Method = "POST";
//这行代码很关键,不设置ContentType将导致后台参数获取不到值
httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
//httpRquest.ContentLength = dataArray.Length;
System.IO.Stream requestStream = null;
if (string.IsNullOrWhiteSpace(sendData) == false)
{
requestStream = httpRquest.GetRequestStream();
requestStream.Write(dataArray, , dataArray.Length);
requestStream.Close();
}
System.Net.WebResponse response = httpRquest.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
backMsg = reader.ReadToEnd(); reader.Close();
reader.Dispose(); requestStream.Dispose();
responseStream.Close();
responseStream.Dispose();
}
catch (Exception)
{
throw;
}
return backMsg;
}
二、HttpClient方式(转自:http://blog.csdn.net/qianmenfei/article/details/37974767)
1、通用http类
using System;
using System.Globalization;
using System.Net;
using System.Text; namespace Test
{
public class HttpCommon
{
/// <summary>
/// Http同步Get同步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="encode">编码(默认UTF8)</param>
/// <returns></returns>
public static string HttpGet(string url, Encoding encode = null)
{
string result; try
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; result = webClient.DownloadString(url);
}
catch (Exception ex)
{
result = ex.Message;
} return result;
} /// <summary>
/// Http同步Get异步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="callBackDownStringCompleted">回调事件</param>
/// <param name="encode">编码(默认UTF8)</param>
public static void HttpGetAsync(string url,
DownloadStringCompletedEventHandler callBackDownStringCompleted = null, Encoding encode = null)
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; if (callBackDownStringCompleted != null)
webClient.DownloadStringCompleted += callBackDownStringCompleted; webClient.DownloadStringAsync(new Uri(url));
} /// <summary>
/// Http同步Post同步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="postStr">请求Url数据</param>
/// <param name="encode">编码(默认UTF8)</param>
/// <returns></returns>
public static string HttpPost(string url, string postStr = "", Encoding encode = null)
{
string result; try
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; var sendData = Encoding.GetEncoding("GB2312").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); var readData = webClient.UploadData(url, "POST", sendData); result = Encoding.GetEncoding("GB2312").GetString(readData); }
catch (Exception ex)
{
result = ex.Message;
} return result;
} /// <summary>
/// Http同步Post异步请求
/// </summary>
/// <param name="url">Url地址</param>
/// <param name="postStr">请求Url数据</param>
/// <param name="callBackUploadDataCompleted">回调事件</param>
/// <param name="encode"></param>
public static void HttpPostAsync(string url, string postStr = "",
UploadDataCompletedEventHandler callBackUploadDataCompleted = null, Encoding encode = null)
{
var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null)
webClient.Encoding = encode; var sendData = Encoding.GetEncoding("GB2312").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); if (callBackUploadDataCompleted != null)
webClient.UploadDataCompleted += callBackUploadDataCompleted; webClient.UploadDataAsync(new Uri(url), "POST", sendData);
}
}
}
2、调用类
using System;
using System.Net;
using System.Text;
using System.Web.UI; namespace Test
{
public partial class WebForm3 : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(HttpCommon.HttpGet("http://localhost:14954/WebForm4.aspx")); //Get同步
HttpCommon.HttpGetAsync("http://localhost:14954/WebForm4.aspx"); //Get异步
HttpCommon.HttpGetAsync("http://localhost:14954/WebForm4.aspx", DownStringCompleted); //Get异步回调 Response.Write(HttpCommon.HttpPost("http://localhost:14954/WebForm4.aspx", "post=POST")); //Post同步
HttpCommon.HttpPostAsync("http://localhost:14954/WebForm4.aspx", "post=POST"); //Post异步
HttpCommon.HttpPostAsync("http://localhost:14954/WebForm4.aspx", "post=POST", UploadDataCompleted); //Post异步回调
} private void DownStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Response.Write(e.Result);
} private void UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
Response.Write(Encoding.GetEncoding("GB2312").GetString(e.Result));
}
}
}
asp.net后台发送HTTP请求的更多相关文章
- 腾讯云图片鉴黄集成到C# SQL Server 怎么在分页获取数据的同时获取到总记录数 sqlserver 操作数据表语句模板 .NET MVC后台发送post请求 百度api查询多个地址的经纬度的问题 try{}里有一个 return 语句,那么紧跟在这个 try 后的 finally {}里的 code 会 不会被执行,什么时候被执行,在 return 前还是后? js获取某个日期
腾讯云图片鉴黄集成到C# 官方文档:https://cloud.tencent.com/document/product/641/12422 请求官方API及签名的生成代码如下: public c ...
- 后台发送http请求通用方法,包括get和post
package com.examsafety.service.sh; import java.io.BufferedReader; import java.io.IOException; import ...
- C#后台发送HTTP请求
using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Syst ...
- 后台发送get请求
第一步:编写Controller,让后台去请求接口 package controller; import java.util.List; import org.springframework.bean ...
- Django(十二)视图--利用jquery从后台发送ajax请求并处理、ajax登录案例
一.Ajax基本概念 [参考]:https://www.runoob.com/jquery/jquery-ajax-intro.html 异步的javascript.在不全部加载某一个页面部的情况下, ...
- 理解ASP.NET Core - 发送Http请求(HttpClient)
注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 前言 在.NET中,我们有很多发送Http请求的手段,如HttpWebRequest.WebC ...
- .NET MVC后台发送post请求
一.WebRequest方式 //设置请求接口 var request = (HttpWebRequest)WebRequest.Create("http://xxx.com/xxx&quo ...
- asp.net 后台 Http POST请求
时间忙,简单些,直接贴代码上图 百度站长平台为站长提供链接提交通道,您可以提交想被百度收录的链接,百度搜索引擎会按照标准处理 http://zhanzhang.baidu.com/linksubmit ...
- C# 后台发送get,post请求及WebApi接收
后台发送get请求 1.发送带参数的get请求 /// <summary> /// 发送get请求 参数拼接在url后面 /// </summary> /// <para ...
随机推荐
- LNMP环境源码搭建
以前LNMP环境是由运维搭建,自己搭建的时候查找了很多资料,这是我见过的最棒的资料,将过程记录下来分享给大家 为啥使用LNMP而不是LAMP下面来谈谈Nginx的技能 Nginx是一个小巧而高效的Li ...
- 【Spring】高级装配
前言 前面讲解了bean的核心装配技术,其可应付很多中装配情况,但Spring提供了高级装配技术,以此实现更为高级的bean装配功能. 高级装配 配置profile bean 将所有不同bean定义放 ...
- Reliability diagrams
Reliability diagrams (Hartmann et al. 2002) are simply graphs of the Observed frequency of an event ...
- java基础解析系列(八)---fail-fast机制及CopyOnWriteArrayList的原理
fail-fast机制及CopyOnWriteArrayList的原理 目录 java基础解析系列(一)---String.StringBuffer.StringBuilder java基础解析系列( ...
- IE9总是弹出“ICBC Anti-Phishing class” 加载项是否要启用还是不启用的提示
解决方法: 后来在通过查询,发现 IcbcDaemon.exe 进程是写在系统服务中的,我们可以在系统的服务管理工具中停止该服务: 1.单击开始,在搜索框中输入 services.msc ,按下回车键 ...
- HDU1411 欧拉四面体
用向量解决: 三角形面积:S=1/2*|x1*y2-x2*y1|; (粗体表示向量) 三棱锥体积:V=1/6*(OA*OB)*OC 不知道哪里去找的代码,毕竟很线性代数矩阵什么的很头疼,晚上 ...
- Java 继承、抽象、接口
一.继承 1. 概述 继承是面向对象的重要特征之一,当多个类中存在相同的属性和行为时,将这些内容抽取到单独一个类中,那多个类中无需再定义这些属性和行为,只需继承那个单独的类即可. 单独的类称为父类或超 ...
- js 将一大段时间均分为很多个小时间段
最近写项目,遇到一个将选中时间段平均分割为若干小段,然后根据小段时间在数据库查询求均值的问题,后台大哥犯懒,非说后台做不了,让我分好传给他ヾ(. ̄□ ̄)ツ゜゜゜好气呦,但还要保持微笑,我就是这么懂礼貌 ...
- cocos2dx - 伤害实现
接上一节内容:cocos2dx - 生成怪物及AI 本节主要讲如何通过创建简单的矩形区域来造成伤害 在小游戏中简单的碰撞需求应用box2d等引擎会显得过于臃肿复杂,且功能不是根据需求定制,还要封装,为 ...
- 我的第一个python web开发框架(8)——项目结构与RESTful接口风格说明
PS:再次说明一下,原本不想写的太啰嗦的,可之前那个系列发布后发现,好多朋友都想马上拿到代码立即能上手开发自己的项目,对代码结构.基础常识.分类目录与文件功能结构.常用函数......等等什么都不懂, ...