HTTP 响应中的无效字符集
Invalid Charset in HTTP response
我正在为 Windows Phone 8.1 编写 C# 应用程序。应用程序向带有 post 数据的网页发送 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: The character set provided in
ContentType is invalid. Cannot read content as string using an invalid
character set. ---> System.ArgumentException: 'ISO8859_1' is not a
supported encoding name."
显然解决方案是使用 GetByteArrayAsync 而不是 PostAsync (),但这样我无法提交 post 数据。
Apparently the solution is to use GetByteArrayAsync instead of PostAsync
不,你可以使用 HttpContent
class
的 ReadAsByteArrayAsync
方法
byte[] data = await response.Content.ReadAsByteArrayAsync();
某些服务器响应可能包含无效字符集,在这种情况下 'ISO8859_1' 无效。解决这种情况的另一种方法是将字符集更改为正确的值,然后再读取为字符串:
responseMessage.Content.Headers.ContentType.CharSet = @"ISO-8859-1";
responseString = await response.Content.ReadAsStringAsync();
我正在为 Windows Phone 8.1 编写 C# 应用程序。应用程序向带有 post 数据的网页发送 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: The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set. ---> System.ArgumentException: 'ISO8859_1' is not a supported encoding name."
显然解决方案是使用 GetByteArrayAsync 而不是 PostAsync (),但这样我无法提交 post 数据。
Apparently the solution is to use GetByteArrayAsync instead of PostAsync
不,你可以使用 HttpContent
class
ReadAsByteArrayAsync
方法
byte[] data = await response.Content.ReadAsByteArrayAsync();
某些服务器响应可能包含无效字符集,在这种情况下 'ISO8859_1' 无效。解决这种情况的另一种方法是将字符集更改为正确的值,然后再读取为字符串:
responseMessage.Content.Headers.ContentType.CharSet = @"ISO-8859-1";
responseString = await response.Content.ReadAsStringAsync();