因为老版本的 .NET 没有 HttpClient,所以只能使用 WebClient 或借助第三方包进行 Web API 的调用。
GET
using (var client = new WebClient())
{
client.Headers[HttpRequestHeaders.Accept] = "application/json";
string result = client.DownloadString("http://example.com/values");
// now use a JSON parser to parse the resulting string back to some CLR object
var todo = JsonConvert.DeserializeObject<Todo>(result);
}
PUT
string data = JsonConvert.SerializeObject(record);
try
{
// 好像是因为官方 Headers 设置存在问题,所以没法把 Content-Type 和 Accept 放在一起初始化
client.Headers["Content-Type"] = "application/json";
client.UploadString("http://example.com/values", WebRequestMethods.Http.Put, data);
}
catch (WebException ex)
{
Logger.Error(ex, $"PUT failed data: {data}");
throw;
}
POST
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.Accept] = "application/json";
var data = Encoding.UTF8.GetBytes("{\"foo\":\"bar\"}");
byte[] result = client.UploadData("http://example.com/values", "POST", data);
string resultContent = Encoding.UTF8.GetString(result, 0, result.Length);
// now use a JSON parser to parse the resulting string back to some CLR object
var content = JsonConvert.DeserializeObject<Content>(resultContent);
}
DELETE
public void DeleteRecord(string id)
{
client.UploadValues($"https://example.com/api/records/{id}", "DELETE",
new NameValueCollection());
}