从HttpResponseMessage获取内容/消息

我试图得到HttpResponseMessage的内容。 它应该是: {"message":"Action '' does not exist!","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 } 

你需要调用GetResponse() 。

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

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

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

这样您就不需要引入任何stream读取器,也不需要任何扩展方法。

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

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

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

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

我希望这可以帮助你;-)

如果你想把它转换成特定的types(例如在testing中),你可以使用ReadAsAsync扩展方法:

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

或跟随同步代码:

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

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

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

您可以使用GetStringAsync方法:

 var uri = new Uri("http://yoururlhere"); var response = await client.GetStringAsync(uri);