我正在尝试从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 Tasksend(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'; using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = client.GetAsync(url).Result) { using (HttpContent content = response.Content) { var json = content.ReadAsStringAsync().Result; } } }
有关完整的详细信息,以及如何async/await
与HttpClient
您一起使用,请阅读此答案的详细信息