我正在尝试从 HTTP 请求获取响应,但我似乎无法做到。我尝试过以下方法:
public Form1() {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("someUrl");
string content = "someJsonString";
HttpRequestMessage sendRequest = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
sendRequest.Content = new StringContent(content,
Encoding.UTF8,
"application/json");
发送消息:
...
client.SendAsync(sendRequest).ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
} // end public Form1()
使用此代码,我取回状态代码和一些标头信息,但我没有取回响应本身。我也尝试过:
HttpResponseMessage response = await client.SendAsync(sendRequest);
但随后我被告知创建一个如下所示的异步方法以使其正常工作
private async Task<string> send(HttpClient client, HttpRequestMessage msg)
{
HttpResponseMessage response = await client.SendAsync(msg);
string rep = await response.Content.ReadAsStringAsync();
}
这是发送“HttpRequest”、获取并打印响应的首选方式吗?我不确定哪种方法是正确的。
这是一种使用
HttpClient
的方法,这应该读取请求的响应,以防请求返回状态200,(请求不是BadRequest
或NotAuthorized
)
string url = 'your url here';
// usually you create on HttpClient per Application (it is the best practice)
HttpClient client = new HttpClient();
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
var json = await content.ReadAsStringAsync();
}
}
欲了解完整详细信息并了解如何将
async/await
与 HttpClient
一起使用,您可以阅读 此答案的详细信息