简体   繁体   English

从 HttpResponseMessage 获取内容/消息

[英]Getting content/message from HttpResponseMessage

I'm trying to get content of HttpResponseMessage.我正在尝试获取 HttpResponseMessage 的内容。 It should be: {"message":"Action '' does not exist,":"success":false} , but I don't know, how to get it out of 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!

In this case txtBlock would have value:在这种情况下 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
}

I think the easiest approach is just to change the last line to我认为最简单的方法就是将最后一行更改为

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

This way you don't need to introduce any stream readers and you don't need any extension methods.这样你就不需要引入任何流阅读器,也不需要任何扩展方法。

You need to call GetResponse() .您需要调用GetResponse()

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

Try this, you can create an extension method like this:试试这个,你可以创建一个这样的扩展方法:

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

and then, simple call the extension method:然后,简单地调用扩展方法:

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

I hope this help you ;-)我希望这对你有帮助;-)

If you want to cast it to specific type (eg within tests) you can use ReadAsAsync extension method:如果您想将其转换为特定类型(例如在测试中),您可以使用ReadAsAsync扩展方法:

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

or following for synchronous code:或以下同步代码:

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

Update: there is also generic option of ReadAsAsync<> which returns specific type instance instead of object-declared one:更新:还有ReadAsAsync<> 的通用选项,它返回特定类型的实例而不是对象声明的实例:

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

By the answer of rudivonstaden由 rudivonstaden 的回答

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

but if you don't want to make the method async you can use但如果你不想使方法异步,你可以使用

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

Wait() it's important, becаuse we are doing async operations and we must wait for the task to complete before going ahead. Wait() 很重要,因为我们正在执行异步操作,我们必须等待任务完成才能继续。

我建议的快速答案是:

response.Result.Content.ReadAsStringAsync().Result

I think the following image helps for those needing to come by T as the return type.我认为下图对那些需要使用T作为返回类型的人有所帮助。

在此处输入图片说明

You can use the GetStringAsync method:您可以使用GetStringAsync方法:

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

Using block:使用块:

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). 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), applies ReadAsStringAsync() method to that content(which is also object of some special type) and, finally, wait for this async task to complete using.Result property once again in order to get final result string and then return this string as our function return. 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;
    }

Shorter version, which does not show the full "transformational" path of our http-request and uses GetStringAsync method of HttpClient object.较短的版本,它不显示我们的 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 to get final string and after that simply returns this string as a function return. 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;
    }

Usage:用法:

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*/

Full code:完整代码:

在此处输入图像描述

Updated answer as of 2022-02:截至 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.

相关问题 HttpResponseMessage StringContent替换消息内容 - HttpResponseMessage StringContent replacing message content 从HttpResponseMessage获取内容以使用c#动态关键字进行测试 - Getting content from HttpResponseMessage for testing using c# dynamic keyword 从HttpResponseMessage.Content读取流式内容 - Reading streamed content from HttpResponseMessage.Content Content-Type 字符集是否未从 HttpResponseMessage 公开? - Is the Content-Type charset not exposed from HttpResponseMessage? 如何从HttpResponseMessage反序列化protobuf内容 - How to deserialize protobuf content from HttpResponseMessage 使用HttpResponseMessage.Content.ReadAsStringAsync()时没有得到内容的全部; - Not getting the entirety of the content when using HttpResponseMessage.Content.ReadAsStringAsync(); 我如何从控制台应用程序中提取 HTTPResponseMessage 内容 - How do i Extract HTTPResponseMessage content from Console App 将内容放在 HttpResponseMessage 对象中? - Put content in HttpResponseMessage object? 在内容 100% 完成之前从 HttpResponseMessage 读取标头 - Read headers from HttpResponseMessage before Content is 100% complete 如何从 HttpResponseMessage 读取应用程序/pdf 内容类型并将其转换为 stream - How to read application/pdf content type from HttpResponseMessage and convert it into stream
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM