jon*_*nes 3 c# asynchronous httpclient
我正在尝试从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");
Run Code Online (Sandbox Code Playgroud)
发送消息:
...
client.SendAsync(sendRequest).ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
} // end public Form1()
Run Code Online (Sandbox Code Playgroud)
使用此代码,我可以获取状态代码和一些标头信息,但无法获取响应本身。我也尝试过:
HttpResponseMessage response = await client.SendAsync(sendRequest);
Run Code Online (Sandbox Code Playgroud)
但是我被告知要创建一个如下所示的异步方法来使其工作
private async Task<string> send(HttpClient client, HttpRequestMessage msg)
{
HttpResponseMessage response = await client.SendAsync(msg);
string rep = await response.Content.ReadAsStringAsync();
}
Run Code Online (Sandbox Code Playgroud)
这是发送“ HttpRequest”,获取并打印响应的首选方式吗?我不确定哪种方法是正确的。
这是一种使用方法HttpClient,如果请求返回状态为200(请求不是BadRequest或NotAuthorized),它应该读取请求的响应。
string url = 'your url here';
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
}
Run Code Online (Sandbox Code Playgroud)
有关完整的详细信息,以及如何async/await与HttpClient您一起使用,请阅读此答案的详细信息
| 归档时间: |
|
| 查看次数: |
18781 次 |
| 最近记录: |