Cle*_*lem 155 c# windows-8 windows-store-apps
我正在尝试获取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!
Run Code Online (Sandbox Code Playgroud)
在这种情况下,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
}
Run Code Online (Sandbox Code Playgroud)
rud*_*den 331
我认为最简单的方法就是将最后一行更改为
txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!
Run Code Online (Sandbox Code Playgroud)
这样您就不需要引入任何流读取器,也不需要任何扩展方法.
Ice*_*ind 61
你需要调用GetResponse().
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
MCu*_*elo 36
试试这个,你可以创建一个像这样的扩展方法:
public static string ContentToString(this HttpContent httpContent)
{
var readAsStringAsync = httpContent.ReadAsStringAsync();
return readAsStringAsync.Result;
}
Run Code Online (Sandbox Code Playgroud)
然后,简单地调用扩展方法:
txtBlock.Text = response.Content.ContentToString();
Run Code Online (Sandbox Code Playgroud)
我希望这能帮助你;-)
如果要将其强制转换为特定类型(例如,在测试中),可以使用ReadAsAsync扩展方法:
object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));
Run Code Online (Sandbox Code Playgroud)
或者跟随同步代码:
object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;
Run Code Online (Sandbox Code Playgroud)
更新:还有ReadAsAsync <>的通用选项,它返回特定的类型实例而不是对象声明的实例:
YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();
Run Code Online (Sandbox Code Playgroud)
由 rudivonstaden 的回答
txtBlock.Text = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)
但如果你不想使方法异步,你可以使用
txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();
Run Code Online (Sandbox Code Playgroud)
Wait() 很重要,因为我们正在执行异步操作,我们必须等待任务完成才能继续。
我建议的快速答案是:
response.Result.Content.ReadAsStringAsync().Result
| 归档时间: |
|
| 查看次数: |
203773 次 |
| 最近记录: |