我正在尝试获取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
}
答案 0 :(得分:294)
我认为最简单的方法就是将最后一行改为
txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!
这样您就不需要引入任何流阅读器,也不需要任何扩展方法。
答案 1 :(得分:56)
您需要致电GetResponse()。
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();
答案 2 :(得分:33)
试试这个,你可以创建一个像这样的扩展方法:
public static string ContentToString(this HttpContent httpContent)
{
var readAsStringAsync = httpContent.ReadAsStringAsync();
return readAsStringAsync.Result;
}
然后,简单地调用扩展方法:
txtBlock.Text = response.Content.ContentToString();
我希望这可以帮到你; - )
答案 3 :(得分:7)
如果您想将其投射到特定类型(例如在测试中),您可以使用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>();
答案 4 :(得分:6)
我建议的快速答案是:
from functools import partial
n = 3
n_round = partial(round, ndigits=3)
n_round(123.4678)
123.468
new_list = list(map(n_round, list_of_floats))
答案 5 :(得分:1)
根据rudivonstaden的答案
`txtBlock.Text = await response.Content.ReadAsStringAsync();`
但是如果您不想使方法异步,则可以使用
`txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();`
等待()很重要,因为我们正在执行异步操作,因此我们必须等待任务完成才能继续。
答案 6 :(得分:1)
答案 7 :(得分:0)
您可以使用GetStringAsync
方法:
var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);