HttpWebRequest(System.Net)模拟HTTP发送POST
相关参考网上很多,但需要理解并转成自己的情况
1 public static string HttpWebRequestPost(string url, string param) 2 { 3 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); 4 Encoding encoding = Encoding.UTF8; 5 byte[] byteArray = Encoding.ASCII.GetBytes(param); 6 string responseData = String.Empty; 7 req.Method = "POST"; 8 req.ContentType = "application/x-www-form-urlencoded"; 9 req.ContentLength = byteArray.Length; 10 11 using (Stream reqStream = req.GetRequestStream()) 12 { 13 reqStream.Write(byteArray, 0, byteArray.Length); 15 } 16 using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) 17 { 18 using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) 19 { 20 responseData = reader.ReadToEnd(); 21 } 22 return responseData; 23 } 24 }
1.第1行param:需要发送的POST参数,需要和对应接收端约定好相应的格式,如本实例为 random=abc&check=faa5bff8a65e359ea863ca1e ,查参考代码时在stackoverflow.com上看到POST要传送到数据格式是这样的 string data = "{\"service\":\"absence.list\", \"company_id\":3}";
2.第5行是注意点需要将发送到数据转成byte[],这里有一个坑,需要使用对应Encoding工具,推测也是和接收请求的服务端相对应的,这里使用了Encoding.ASCII.GetBytes(param);参考代码中大多是使用了UTF8Encoding对象的.GetBytes(data)方法.
相关参考:获取UTF8Encoding对象两种coding
UTF8Encoding enc = new UTF8Encoding(); byte[] buf = enc.GetBytes(data); //方式二 byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
3.第8行需要根据实际情况调整,其它参考值xxx.ContentType = "application/json; charset=UTF-8";
4.11至15行HttpWebRequest发送POST请求的必须套路,即将发送参数写入输出流,看到不少大同小异的编程风格
5. 第16行req.GetResponse()核心方法,将请求真正发送出去,然后从响应流中读取数据
附GET请求
public string HttpWebRequestGet(string url, string param) { param = param.IndexOf('?') > -1 ? (param) : ("?" + param); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + param); Encoding encoding = Encoding.UTF8; string responseData = String.Empty; req.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { responseData = reader.ReadToEnd(); } return responseData; } }
end