Get 请求
private async Task<List<Demo>> GetResource(HttpClient httpClient)
{
var response = await httpClient.GetAsync("api/demos");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var demos = JsonConvert.DeserializeObject<List<Demo>>(content);
return demos;
}
局部使用自定义请求头
private async Task<List<Demo>> GetResourceThroughHttpRequestMessage(HttpClient httpClient)
{
var request = new HttpRequestMessage(HttpMethod.Get,"api/demos");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var serializer = new XmlSerializer(typeof(List<Demo>));
var demos = (List<Demo>)serializer.Deserialize(new StringReader(content));
return demos;
}
Post 请求
简洁方式
private async Task CreateResource(HttpClient httpClient)
{
var demoToCreate = new DemoForCreation()
{
Title = "some title",
Description = "some description"
};
var response = await _httpClient.PostAsync(
"api/demos",
new StringContent(
JsonConvert.SerializeObject(demoToCreate),
Encoding.UTF8,
"application/json"));
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var demo = JsonConvert.DeserializeObject<Demo>(content);
}
HttpRequestMessage 方式
private async Task CreateResource(HttpClient httpClient)
{
var demoToCreate = new DemoForCreation()
{
Title = "some title",
Description = "some description"
};
var serializedDemoToCreate = JsonConvert.SerializeObject(demoToCreate);
var request = new HttpRequestMessage(HttpMethod.Post,"api/demos");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Content = new StringContent(serializedDemoToCreate);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var serializer = new XmlSerializer(typeof(Demo));
var demo = (Demo)serializer.Deserialize(new StringReader(content));
}