C# Http请求
先看客户端Http请求之HttpWebRequest
using System.IO; using System.Net; using System.Text; public class HttpHelper { public static string Request(string data, string url) { return Request(Encoding.GetEncoding("UTF-8").GetBytes(data), url); } public static string Request(byte[] data, string url) { string result = string.Empty; //创建一个客户端的Http请求实例 HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; request.ContentLength = data.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); //获取当前Http请求的响应实例 HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8"))) { result = reader.ReadToEnd(); } responseStream.Close(); return result; } }
data是待传入的Http实体主体的内容,例如在进行微信支付统一下单时需要传递给微信端的Xml字符串,不传可以写空字符串"";url是所请求的Http地址,例如https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx78b0b7。
与客户端Http请求类HttpWebRequest相对的服务端Http请求类是HttpRequest。HttpApplication、HttpContext、Page、UserControl类的Request属性都是HttpRequest类的实例。HttpRequest类使得Asp.Net能够读取客户端(如浏览器或使用了HttpWebRequest类的客户端程序)在Web请求期间发送的Http值。常见的Http值是客户端以Get方式传来的Url参数、Post方式提交过来的表单项和文件;不常见的Http值则是实体主体内容,例如前面关于HttpWebRequest介绍中提到在进行微信支付统一下单时需要向Http实体主体中写入内容,不清楚微信端如何接收这个Http实体主体,但如果是Asp.Net来接收的话就用HttpRequest类的InputStream属性,在微信支付成功后微信系统会回调商户后台的一个特定接口文件以通知商户后台当前订单已支付完成,此处回调时微信系统会向该特定接口文件写入了一个Xml字符串形式的实体主体内容,如下模拟一个Http实体主体内容的获取:
客户端:
HttpHelper.Request("<xml>data</xml>","http://www.xxx.com/test.aspx?key=value");
服务端:
StreamReader reader = new StreamReader(Request.InputStream);
string xmlStr = reader.ReadToEnd();