HttpWebRequest的GET和POST方法
命名空间: System.Net,这是.NET创建者最初开发用于使用HTTP请求的标准类。使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts, cookies, headers, protocols。
GET请求就很简单易懂啦,如果需要传参,在URL末尾加上“?+参数名=参数值”即可,需要注意的是POST请求。
POST请求参数类型有多个,设置不正确会发生错误的,一般第三方接口都是以JSON交换数据,请求中的参数设置涉及到了Stream流的一些知识点
1
|
httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length); |
这一行的意思是将“bs”从Request的“0”位置中开始写入,长度为“bs.Length”,说白了就是把参数数据加入到请求数据中。
string url = "http://www.webxml.com.cn/WebServices/WeatherWS.asmx/"; string postMethod = "getSupportCityDataset";//方法名 string postDataName = "theRegionCode";//参数名 string postDataValue = "3118";//参数值
string recGetstr= HttpGet(url,postMethod,postDataName,postDataValue); //调用GET
string recPoststr= HttpPost(url,postMethod,postDataName,postDataValue);//调用POST
public string HttpGet(string Url, string postMethod,string postDataName, string postDataValue) { if (postMethod.Length>0) { Url += postMethod; } if (postDataName.Length>0) { Url += "?" + postDataName; } if (postDataValue.Length>0) { Url += "=" + postDataValue; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; request.Timeout = 10000; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
public string HttpPost(string url, string postMethod, string postDataName, string postDataValue) { if (postMethod.Length>0) { url += postMethod; } string data = postDataName + "=" + postDataValue; HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); //字符串转换为字节码 byte[] bs = Encoding.UTF8.GetBytes(data); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; //参数数据长度 httpWebRequest.ContentLength = bs.Length; //设置请求类型 httpWebRequest.Method = "POST"; //设置超时时间 httpWebRequest.Timeout = 20000; //将参数写入请求地址中 httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length); //发送请求 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); //读取返回数据 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8); string responseContent = streamReader.ReadToEnd(); streamReader.Close(); httpWebResponse.Close(); httpWebRequest.Abort(); return responseContent; }