[英]HttpResponseMessage StringContent replacing message content
[英]Getting content/message from 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
}
我认为最简单的方法就是将最后一行更改为
txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!
这样你就不需要引入任何流阅读器,也不需要任何扩展方法。
您需要调用GetResponse() 。
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();
试试这个,你可以创建一个这样的扩展方法:
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>();
由 rudivonstaden 的回答
txtBlock.Text = await response.Content.ReadAsStringAsync();
但如果你不想使方法异步,你可以使用
txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();
Wait() 很重要,因为我们正在执行异步操作,我们必须等待任务完成才能继续。
我建议的快速答案是:
response.Result.Content.ReadAsStringAsync().Result
您可以使用GetStringAsync
方法:
var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);
使用块:
using System;
using System.Net;
using System.Net.Http;
This Function will create new HttpClient object, set http-method to GET, set request URL to the function "Url" string argument and apply these parameters to HttpRequestMessage object (which defines settings of SendAsync method). Last line: function sends async GET http request to the specified url, waits for response-message's.Result property(just full response object: headers + body/content), gets.Content property of that full response(body of request, without http headers),将 ReadAsStringAsync() 方法应用于该内容(这也是一些特殊类型的 object),最后,再次等待此异步任务完成 using.Result 属性以获得最终结果字符串,然后返回此字符串作为我们的 function 返回。
static string GetHttpContentAsString(string Url)
{
HttpClient HttpClient = new HttpClient();
HttpRequestMessage RequestMessage = new HttpRequestMessage(HttpMethod.Get, Url);
return HttpClient.SendAsync(RequestMessage).Result.Content.ReadAsStringAsync().Result;
}
较短的版本,它不显示我们的 http 请求的完整“转换”路径,并使用 HttpClient object 的 GetStringAsync 方法。 Function just creates new instance of HttpClient class (an HttpClient object), uses GetStringAsync method to get response body(content) of our http request as an async-task result\promise, and then uses.Result property of that async-task-result得到最终的字符串,然后简单地将这个字符串作为 function 返回。
static string GetStringSync(string Url)
{
HttpClient HttpClient = new HttpClient();
return HttpClient.GetStringAsync(Url).Result;
}
用法:
const string url1 = "https://microsoft.com";
const string url2 = "https://stackoverflow.com";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; /*sets TLC protocol version explicitly to modern version, otherwise C# could not make http requests to some httpS sites, such as https://microsoft.com*/
Console.WriteLine(GetHttpContentAsString(url1)); /*gets microsoft main page html*/
Console.ReadLine(); /*makes some pause before second request. press enter to make second request*/
Console.WriteLine(GetStringSync(url2)); /*gets stackoverflow main page html*/
Console.ReadLine(); /*press enter to finish*/
完整代码:
截至 2022 年 2 月的更新答案:
var stream = httpResponseMessage.Content.ReadAsStream();
var ms = new MemoryStream();
stream.CopyTo(ms);
var responseBodyBytes = ms.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.