C#发送简单的post、get请求
- POST发送请求及接受响应流程
- 根据目标地址址创建HttpWebRequest对象
- 设置响应的请求参数------Method、ContentType 等
- 使用HttpWebRequest对象获取请求流并且写入消息体
- 使用HttpWebRequest对象获取响应流并读取流中数据(在获取过程中就是发送请求并接受响应)
- GET发送请求及接受响应流程
- 把目标地址和查询字符串拼接在一起(如果有查询字符串)使用拼接的字符串创建HttpWebRequest对象
- 设置响应的请求参数------Method、ContentType 等
- 使用HttpWebRequest对象获取响应流并读取流中数据(在获取过程中就是发送请求并接受响应)
以下为代码:
两个请求方法 和读取方法
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
/// <summary>
/// 发送http post请求
/// </summary>
/// <param name="url">地址</param>
/// <param name="parameters">查询参数集合</param>
/// <returns></returns>
public HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
request.Method = "POST";//请求方式
request.ContentType = "application/x-www-form-urlencoded";//链接类型
//构造查询字符串
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
bool first = true;
foreach (string key in parameters.Keys)
{
if (!first)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
first = false;
}
}
byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
//写入请求流
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 发送http Get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static HttpWebResponse CreateGetHttpResponse(string url)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";//链接类型
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 从HttpWebResponse对象中提取响应的数据转换为字符串
/// </summary>
/// <param name="webresponse"></param>
/// <returns></returns>
public string GetResponseString(HttpWebResponse webresponse)
{
using (Stream s = webresponse.GetResponseStream())
{
StreamReader reader = new StreamReader(s, Encoding.UTF8);
return reader.ReadToEnd();
}
}
|
调用
1
2
3
4
5
6
7
8
|
//post请求并调用
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("id", "4");
textBox1.Text = GetResponseString(CreatePostHttpResponse("https://www.baidu.com/", dic));
//get请求并调用
textBox3.Text = GetResponseString(CreateGetHttpResponse("https://i.cnblogs.com/EditPosts.aspx?opt=1"));
|