查看 HttpClient.PostAsync 的响应正文

Posted

技术标签:

【中文标题】查看 HttpClient.PostAsync 的响应正文【英文标题】:View response body for HttpClient.PostAsync 【发布时间】:2021-01-17 21:35:28 【问题描述】:

我是 Postman 中的一个 POST,它生成以下 Curl:

curl --location --request POST 'https://authqa.cqi.newry.me.com/as/token.oauth2' \
--header 'Authorization: Basic QVBJX0JURUNSRUZEQVRBOlAzNkNEAAE3RVdGUzRPT0NLQlQ0SERaS1pGRTZHTksyQkNJTFVJWT0=' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: PF=mgvtuOC0jyPx3Lbrmw1hTX; BIGipServerauthqa-9031=1948242442.18211.0000' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'charset=utf-8'

它返回以下正文:


    "access_token": "generated_token",
    "token_type": "Bearer",
    "expires_in": 1799

我正在尝试使用 HttpClient 在 C# 中做同样的事情。

这是 POST 完成的地方:

var body = new StringContent("grant_type=client_credentials", Encoding.UTF8,
                "application/x-www-form-urlencoded");
var httpResponseMessage = await _client.PostAsync("sa/token.oauth2", body);

我通过httpResponseMessage.ToString() 得到以下信息。

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
 
   Date: Sun, 17 Jan 2021 21:19:39 GMT
   X-Frame-Options: SAMEORIGIN
   Strict-Transport-Security: max-age=31536000
   Content-Security-Policy: frame-ancestors *.cmegroup.com *.chicago.cme.com
   X-XSS-Protection: 1;mode=block
   Cache-Control: no-store, no-cache
   Pragma: no-cache
   Set-Cookie: PF=4sugakrnEHwY5zWIXYasGo;Path=/;Secure;HttpOnly;SameSite=None
   Set-Cookie: BIGipServerauthqa-9031=1897910794.18211.0000; path=/; Httponly; Secure
   Transfer-Encoding: chunked
   Expires: Thu, 01 Jan 1970 00:00:00 GMT
   Content-Type: application/json; charset=utf-8

我看不到上面发布的响应正文,但我怀疑它是Content: System.Net.Http.HttpConnectionResponseContent。虽然不知道怎么看。谁能告诉我我如何看待上述身体?

【问题讨论】:

这能回答你的问题吗? How to read HttpResponseMessage content as text 【参考方案1】:

HttpClientResponse 包含内容,您可以这样阅读:

var body = new StringContent("grant_type=client_credentials", Encoding.UTF8,
                "application/x-www-form-urlencoded");
var httpResponseMessage = await _client.PostAsync("sa/token.oauth2", body);
var responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); // here you can read content as string
...

另请查看here 了解更多信息。

【讨论】:

【参考方案2】:

httpResponseMessage.Content.ReadAsStringAsync().Result 会输出我想要的,但它被阻塞了。

var response = await client.PostAsync("sa/token.oauth2", body);
var content = await response.Content.ReadAsStringAsync();

请注意,您通常应该使用await - 而不是.Result

见How to read HttpResponseMessage content as text

【讨论】:

请不要提倡异步 I/O 上的阻塞操作。

以上是关于查看 HttpClient.PostAsync 的响应正文的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient.PostAsync 的字符编码问题

HttpClient.PostAsync 崩溃应用。如何捕捉异常?

如何使用 HttpClient.PostAsync 发送 XML 内容?

HttpClient.PostAsync 无响应且无异常

为啥 HttpClient.PostAsync 似乎将请求作为 GET 而不是 POST 发送?

如何等待PostAsync返回?