除了使用 WebRequest 对象可以给服务器发送POST,GET请求外,还可以使用HttpClient对象。
1. 使用 HttpClient 发送GET请求
下测试代码演示了发送一个简单的Http Get 请求,接受HTTP 响应数据。
using System.Net;
using System.Net.Http;
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
var content = await client.GetStringAsync("http://webcode.me");
Console.WriteLine(content);
}
}
使用 HTTPClient的GetStringAsync 执行一个异步的请求。
返回测试的网页源码:
Today is a beautiful day. We go swimming and fishing.
Hello there. How are you?
2. 使用 HttpClient 发送POST请求
需要添加如下引用:
using System.Net;
using System.Net.Http;
using Newtonsoft.Json; //第3方库
基本步骤:
(1) 创建一个对象模型
(2) 实例化一个模型对象
(3) 序列化模型对象
(4) 创建StringContent实例
(5) 创建HTTP Client对象
(6) 使用Client对象向指定URL POST StringContent数据
(7) 获取响应数据
完整代码如下:
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
//数据模型
class User
{
public string Name { get; set; }
public string Occupation { get; set; }
public User(string name, string occupation)
{
Name = name;
Occupation = occupation;
}
public override string ToString()
{
return $"{Name}: {Occupation}";
}
}
static async Task Main(string[] args)
{
var user = new User("John Doe", "gardener");
var json = JsonConvert.SerializeObject(user);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "https://httpbin.org/post";
using (var client = new HttpClient())
{
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
}
输出:
{
"args": {},
"data": "{\"Name\":\"John Doe\",\"Occupation\":\"gardener\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "43",
"Content-Type": "application/json; charset=utf-8",
"Host": "httpbin.org",
"X-Amzn-Trace-Id": "Root=1-61b14aba-47977f4550bfeb7573bd1043"
},
"json": {
"Name": "John Doe",
"Occupation": "gardener"
},
"origin": "180.161.88.74",
"url": "https://httpbin.org/post"
}
可以看到将对象以Json方式发送到服务器。