我试图获得HttpResponseMessage的内容。它应该是:{"message":"Action "不存在!","success":false},但我不知道,如何从HttpResponseMessage中获取它。

HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://****?action=");
txtBlock.Text = Convert.ToString(response); //wrong!

在这种情况下,txtBlock的值是:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Vary: Accept-Encoding
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Date: Wed, 10 Apr 2013 20:46:37 GMT
  Server: Apache/2.2.16
  Server: (Debian)
  X-Powered-By: PHP/5.3.3-7+squeeze14
  Content-Length: 55
  Content-Type: text/html
}

当前回答

我认为最简单的方法就是把最后一行改成

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

这样就不需要引入任何流阅读器,也不需要任何扩展方法。

其他回答

鲁迪翁斯塔登的回答

txtBlock.Text = await response.Content.ReadAsStringAsync();

但如果你不想让方法异步,你可以使用

txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();

Wait()很重要,因为我们正在进行异步操作,必须等待任务完成后才能继续。

试试这个,你可以创建一个像这样的扩展方法:

    public static string ContentToString(this HttpContent httpContent)
    {
        var readAsStringAsync = httpContent.ReadAsStringAsync();
        return readAsStringAsync.Result;
    }

然后,简单地调用扩展方法:

txtBlock.Text = response.Content.ContentToString();

我希望这对你有帮助;-)

如果你想将它转换为特定的类型(例如在测试中),你可以使用ReadAsAsync扩展方法:

object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));

对于同步代码:

object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;

更新:ReadAsAsync<>还有一个通用选项,它返回特定类型的实例,而不是对象声明的实例:

YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();

你需要调用GetResponse()。

Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();

我认为最简单的方法就是把最后一行改成

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

这样就不需要引入任何流阅读器,也不需要任何扩展方法。