HttpResponseMessage获取请求响应体内容
问题描述
使用httpClient获取的HttpResponseMessage类型的response,直接对其toString()获取的是请求的响应头,并没有获取响应体的内容
解决办法
HttpResponseMessage.Content 属性声明 HTTP 响应的内容。HttpContent.ReadAsStringAsync 方法将 HTTP 内容作为异步操作写入到字符串中。
参考Demo
下面以Azure Face API为案例简要介绍其使用方法
using System;
using System.Net.Http;
using System.Text;
using System.Web;
namespace FaceApiDemo
{
class Program
{
static void Main(string[] args)
{
MakeRequest();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<key>");//Face API key
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "age";
var uri = "https://api.cognitive.azure.cn/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{\"url\":\"http://imgsrc.baidu.com/baike/pic/item/4034970a304e251ff1e3819aa486c9177f3e53bf.jpg\"}");//图片URL
using (var content = new ByteArrayContent(byteData))
{
response = await client.PostAsync(uri, content);
}
//response result
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine("response:" + result);
}
}
}