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

时间:2013-09-29 19:55:55

标签: c# character-encoding httpclient content-type

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

使用HttpWebRequest时,charset会在HttpWebResponse.CharacterSet属性中公开,就像这样

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

您也可以从WebResponse.ContentType属性或HttpWebResponse.Headers中的内容类型标题中找到它。

使用HttpClientContentType标题中似乎缺少字符集。

以下是我用于HttpClient的代码:

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

CharSet属性始终为nullHttpResponseMessage具有Headers属性,但不包含内容类型标头。 HttpResponseMessage.Content也有一个Headers属性,它似乎包含内容类型标题,但该标题显示"Content-Type: text/html" - 它没有charset部分。

对于相同的url使用HttpWebResponse的第一种方法,我得到了Content-Type标头的charset部分。我错过了什么吗?

4 个答案:

答案 0 :(得分:4)

我想在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());

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

HttpClient故意不暴露字符集。确切地说,它不能。它是异步的,所以当它连接到服务器时,它会一直等到响应。除了" chunk"之外,它不知道除了HttpResponseMessage中的TransferEncoding之外的charset或其他任何东西。或" zip"。

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

答案 3 :(得分:0)

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

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