【问题标题】:Invalid Charset in HTTP responseHTTP 响应中的字符集无效
【发布时间】:2015-06-09 16:30:45
【问题描述】:

我正在为 Windows Phone 8.1 编写一个 C# 应用程序。应用程序向包含发布数据的网页发送 http 请求,但是,当我将请求内容复制到字符串时,它会引发异常。

这是代码,

var values = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("username", "usernameHere"),
        new KeyValuePair<string, string>("password", "passwordHere"),
    };

var httpClient = new HttpClient(new HttpClientHandler());
var response = await httpClient.PostAsync(new Uri(LOGIN_URL), new FormUrlEncodedContent(values));

if (response.IsSuccessStatusCode)
{
    string responseString = "";

    try
    {
        responseString = await response.Content.ReadAsStringAsync();
    }

    catch (Exception e)
    {
        MessageBox.Show("Exception caught " + e);
    }
}

错误是,

"System.InvalidOperationException: 中提供的字符集 内容类型无效。无法使用无效的字符串将内容读取为字符串 字符集。 ---> System.ArgumentException: 'ISO8859_1' 不是 支持的编码名称。”

显然解决方案是使用 GetByteArrayAsync 而不是 PostAsync (How to change the encoding of the HttpClient response),但是这样我无法提交 post 数据。

【问题讨论】:

    标签: c# .net http


    【解决方案1】:

    显然解决方案是使用 GetByteArrayAsync 而不是 PostAsync

    不可以使用HttpContent类的ReadAsByteArrayAsync方法

    byte[] data = await response.Content.ReadAsByteArrayAsync();
    

    【讨论】:

      【解决方案2】:

      某些服务器响应可能包含无效字符集,在这种情况下,“ISO8859_1”无效。解决这种情况的另一种方法是在读取为字符串之前将字符集更改为正确的值:

      responseMessage.Content.Headers.ContentType.CharSet = @"ISO-8859-1";
      responseString = await response.Content.ReadAsStringAsync();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-03
        • 1970-01-01
        • 2021-09-12
        • 2017-12-27
        • 1970-01-01
        • 2018-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多