HttpClient 检索所有标头 [英] HttpClient retrieve all headers

查看:25
本文介绍了HttpClient 检索所有标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在研究 API 包装器.如果我发送了错误的 Consumer Key,服务器将在标头中返回 Status 作为 403 Forbidden.它还将传递自定义标头.我如何实际检索这些自定义标头?

Currently, I am working on API wrapper. If I send a bad Consumer Key, the server will return Status as 403 Forbidden in the header. It will also pass custom headers. How do I actually retrieve these custom headers?

这是从服务器收到的响应.

This is the response receive from the server.

Cache-Control: private
Date: Wed,  01 May 2013 14:36:17 GMT
P3P: policyref="/w3c/p3p.xml",  CP="ALL CURa ADMa DEVa OUR IND UNI COM NAV INT STA PRE"
Server: Apache/2.2.23 (Amazon)
Status: 403 Forbidden
X-Error: Invalid consumer key.
X-Error-Code: 152
X-Powered-By: PHP/5.3.20
Connection: keep-alive

我需要检索X-ErrorX-Error-Code.目前,我使用 HttpClient 类来处理请求.如果我在 VS Studio 2012 中查看 Quick Watch 下的标题响应,我会发现它是这样的

I need to retrieve the X-Error and X-Error-Code. Currently, I am using HttpClient class to process the request. If I watch the headers respond under Quick Watch in VS Studio 2012, I could find it like this

((System.Net.Http.Headers.HttpHeaders)(response.Headers)).headerStore["X-Error-Code"].ParsedValue

有没有其他方法可以做到这一点?

Is there any other way to do this?

headerStore 不能通过代码访问,因为这是私有字段.我只能通过快速观看"窗口访问它.

headerStore is not accessible thru code as this is private field. I only get access to it through the Quick Watch window.

这是我的请求片段:

var response = await _httpClient.PostAsync("/v3/oauth/request", content);

推荐答案

好吧,HttpResponseMessage.Headers 返回一个 HttpResponseHeaders 参考,因此您应该能够使用 GetValues()

string error = response.Headers.GetValues("X-Error").FirstOrDefault();
string errorCode = response.Headers.GetValues("X-Error-Code").FirstOrDefault();

这篇关于HttpClient 检索所有标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆