除了使用 WebRequest 对象可以给服务器发送POST,GET请求外,还可以使用HttpClient对象。

1. 使用 HttpClient 发送GET请求

下测试代码演示了发送一个简单的Http Get 请求,接受HTTP 响应数据。

  1. using System.Net;
  2. using System.Net.Http;
  3. static async Task Main(string[] args)
  4. {
  5. using (var client = new HttpClient())
  6. {
  7. var content = await client.GetStringAsync("http://webcode.me");
  8. Console.WriteLine(content);
  9. }
  10. }

使用 HTTPClient的GetStringAsync 执行一个异步的请求。
返回测试的网页源码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>My html page</title>
  7. </head>
  8. <body>
  9. <p>
  10. Today is a beautiful day. We go swimming and fishing.
  11. </p>
  12. <p>
  13. Hello there. How are you?
  14. </p>
  15. </body>
  16. </html>

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) 获取响应数据
完整代码如下:

  1. using System.Net;
  2. using System.Net.Http;
  3. using Newtonsoft.Json;
  4. //数据模型
  5. class User
  6. {
  7. public string Name { get; set; }
  8. public string Occupation { get; set; }
  9. public User(string name, string occupation)
  10. {
  11. Name = name;
  12. Occupation = occupation;
  13. }
  14. public override string ToString()
  15. {
  16. return $"{Name}: {Occupation}";
  17. }
  18. }
  19. static async Task Main(string[] args)
  20. {
  21. var user = new User("John Doe", "gardener");
  22. var json = JsonConvert.SerializeObject(user);
  23. var data = new StringContent(json, Encoding.UTF8, "application/json");
  24. var url = "https://httpbin.org/post";
  25. using (var client = new HttpClient())
  26. {
  27. var response = await client.PostAsync(url, data);
  28. string result = response.Content.ReadAsStringAsync().Result;
  29. Console.WriteLine(result);
  30. }
  31. }

输出:

  1. {
  2. "args": {},
  3. "data": "{\"Name\":\"John Doe\",\"Occupation\":\"gardener\"}",
  4. "files": {},
  5. "form": {},
  6. "headers": {
  7. "Content-Length": "43",
  8. "Content-Type": "application/json; charset=utf-8",
  9. "Host": "http://httpbin.org",
  10. "X-Amzn-Trace-Id": "Root=1-61b14aba-47977f4550bfeb7573bd1043"
  11. },
  12. "json": {
  13. "Name": "John Doe",
  14. "Occupation": "gardener"
  15. },
  16. "origin": "180.161.88.74",
  17. "url": "https://httpbin.org/post"
  18. }

可以看到将对象以Json方式发送到服务器。