因为老版本的 .NET 没有 HttpClient,所以只能使用 WebClient 或借助第三方包进行 Web API 的调用。

GET

  1. using (var client = new WebClient())
  2. {
  3. client.Headers[HttpRequestHeaders.Accept] = "application/json";
  4. string result = client.DownloadString("http://example.com/values");
  5. // now use a JSON parser to parse the resulting string back to some CLR object
  6. var todo = JsonConvert.DeserializeObject<Todo>(result);
  7. }

PUT

  1. string data = JsonConvert.SerializeObject(record);
  2. try
  3. {
  4. // 好像是因为官方 Headers 设置存在问题,所以没法把 Content-Type 和 Accept 放在一起初始化
  5. client.Headers["Content-Type"] = "application/json";
  6. client.UploadString("http://example.com/values", WebRequestMethods.Http.Put, data);
  7. }
  8. catch (WebException ex)
  9. {
  10. Logger.Error(ex, $"PUT failed data: {data}");
  11. throw;
  12. }

POST

  1. using (var client = new WebClient())
  2. {
  3. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  4. client.Headers[HttpRequestHeader.Accept] = "application/json";
  5. var data = Encoding.UTF8.GetBytes("{\"foo\":\"bar\"}");
  6. byte[] result = client.UploadData("http://example.com/values", "POST", data);
  7. string resultContent = Encoding.UTF8.GetString(result, 0, result.Length);
  8. // now use a JSON parser to parse the resulting string back to some CLR object
  9. var content = JsonConvert.DeserializeObject<Content>(resultContent);
  10. }

DELETE

  1. public void DeleteRecord(string id)
  2. {
  3. client.UploadValues($"https://example.com/api/records/{id}", "DELETE",
  4. new NameValueCollection());
  5. }

参考