C#基于HttpWebRequest实现发送HTTP请求的方法。分享给大家供大家参考,具体如下:
调用第三方API的时候要用到HttpWebRequest类发送HTTP请求,网上查阅一番后大致了解了该类的用法,现记录如下。
首先引入HttpWebRequest类,System.IO类
1
2
|
using HttpWebRequest
using System.IO
|
GET请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/// <summary>
/// 发送GET请求
/// </summary>
/// <param name="url">请求URL,如果需要传参,在URL末尾加上“?+参数名=参数值”即可</param>
/// <returns></returns>
static string HttpGet( string url)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpWebRequest.Method = "GET" ;
httpWebRequest.Timeout = 20000;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
string responseContent = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
return responseContent;
}
|
POST请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/// <summary>
/// 发送POST请求
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="data">请求参数</param>
/// <returns></returns>
static string HttpPost( string url, string data)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
byte [] bs = Encoding.UTF8.GetBytes(data);
httpWebRequest.ContentType = "application/json" ;
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;
}
|
GET请求就很简单易懂啦,如果需要传参,在URL末尾加上“?+参数名=参数值”即可,需要注意的是POST请求。
POST请求参数类型有多个,设置不正确会发生错误的,一般第三方接口都是以JSON交换数据,按我上面那样写就没错了。请求中的参数设置涉及到了Stream流的一些知识点
1
|
httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length);
|
这一行的意思是将“bs”从Request的“0”位置中开始写入,长度为“bs.Length”,说白了就是把参数数据加入到请求数据中。
开始写入,长度为“bs.Length”,说白了就是把参数数据加入到请求数据中。