繁体   English   中英

Content-Type 字符集是否未从 HttpResponseMessage 公开?

[英]Is the Content-Type charset not exposed from HttpResponseMessage?

我正在将一些代码从使用HttpWebRequest转换为HttpClient 我遇到的一个问题是从内容类型响应 header 获取字符集。

使用HttpWebRequest时,字符集在HttpWebResponse.CharacterSet属性中公开,如下所示

using (WebResponse response = await this.webRequest.GetResponseAsync())
{
     string characterSet = ((HttpWebResponse)response).CharacterSet;

您还可以从WebResponse.ContentType属性或从HttpWebResponse.Headers中的内容类型 header 获取它。

使用HttpClient时, ContentType header 中似乎缺少字符集。

这是我用于HttpClient的代码:

using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
    using (HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseContentRead))
    {
        charset = httpResponseMessage.Content.Headers.ContentType.CharSet;

CharSet 属性始终为null HttpResponseMessage有一个Headers属性,但它不包含内容类型HttpResponseMessage.Content也有一个 Headers 属性,它似乎包含内容类型 header,但 header 显示"Content-Type: text/html" - 它没有字符集部分。

对同一个 url 使用HttpWebResponse的第一种方法,我得到了 Content-Type header 的字符集部分。我错过了什么吗?

我想在 HttpResponseMessage 中发出字符集,因为你的问题是谷歌上的第一个问题,我在下面几页找到了答案,这里是代码

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
httpResponseMessage.Content.Headers.ContentType.CharSet = Encoding.UTF8.HeaderName;
httpResponseMessage.Content.Headers.Add("CodePage", Encoding.UTF8.CodePage.ToString());

您可以通过以下方式获取:

var contentType = response.Content.Headers.GetValues("Content-Type").First());

我相信从服务器返回的Content-Type标头必须包含像'text/html;charset=UTF-8'这样的'text/html;charset=UTF-8' ,以便它显示在CharSet属性中。 在像 Fiddler ( http://www.telerik.com/fiddler ) 这样的工具中检查原始响应可能会有所帮助。

感谢您帮助我找到HttpResponseMessage对象中Content-Type标头的位置!

HttpClient 有意不公开字符集。 确切地说,它不能。 它是异步的,所以当它连接到服务器时,它会等待直到响应。 它不知道字符集或除 HttpResponseMessage 中的 TransferEncoding 之外的任何其他内容,它不包含除“chunk”或“zip”之外的任何内容。

因此,要获得响应主体的编码,我们应该将其读取到变量中,然后仔细查看。

由于 Content-Type 可以是类型数组,您可能想检查其中任何一个的有效性,但这是假设服务器编写正确并且不会混合类型和字符集

var isJson = response.Content.Headers.GetValues("Content-Type").Any(x=>x.Contains("json"));

var isCharsetUTF8 = response.Content.Headers.GetValues("Content-Type").Any(x=>x.Contains("charset=UTF-8"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM