访问HttpResponseMessage的内容

时间:2016-06-08 16:56:24

标签: c#

我想打印HTTPResponseMessage的内容。

class Requests
{
    public static async Task SendRequest(int port, string path, KVPairs kvPairs)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(BASE_ADDRESS + port);
            var request = new HttpRequestMessage(HttpMethod.Put, path);

            request.Content = new FormUrlEncodedContent(kvPairs);

            ProcessResponse(await client.SendAsync(request));
        }
    }

    public static void ProcessResponse (HttpResponseMessage response)
    {
        Console.WriteLine(response.Content.ReadAsStringAsync());
    }
}

SendRequest完美无缺。但ProcessResponse()打印System.Threading.Tasks.Task\`1[System.String]

如何访问和打印回复内容?谢谢!

2 个答案:

答案 0 :(得分:1)

您需要等待response.Content.ReadAsStringAsync()返回的任务,这反过来意味着您需要ProcessResponse async方法,并等待它。否则,您正在打印任务对象本身,这不是您想要的。

请注意下面的3个更改(请参阅注释):

public static async Task SendRequest(int port, string path, KVPairs kvPairs)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(BASE_ADDRESS + port);
        var request = new HttpRequestMessage(HttpMethod.Put, path);

        request.Content = new FormUrlEncodedContent(kvPairs);

        await ProcessResponse(await client.SendAsync(request)); // added await here
    }
}

public static async Task ProcessResponse (HttpResponseMessage response) // added async Task here
{
    Console.WriteLine(await response.Content.ReadAsStringAsync()); // added await here
}

答案 1 :(得分:0)

此解决方案应该适合您。 Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

您应该使用await或wait()来获取响应,然后像这样处理它:

var jsonString = response.Content.ReadAsStringAsync();

jsonString.Wait();

model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);