2015-04-04 373 views
2

我正在为Windows Phone 8.1编写一个C#应用程序。应用程序向带有发布数据的网页发送http请求,但是,当我将请求内容复制到字符串时,它会引发异常。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:字符集 ContentType的规定是无效的使用无效 无法读取内容为字符串。字符集---> System.ArgumentException:'ISO8859_1'不是 支持的编码名称。“

显然,解决方案是使用,而不是PostAsync(How to change the encoding of the HttpClient response)GetByteArrayAsync,但这种方式我不能提交后的数据。

回答

4

显然,解决方案是使用GetByteArrayAsync代替PostAsync

不,你可以使用方法类的HttpContentReadAsByteArrayAsync

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

某些服务器响应可以有无效的字符集,在这种情况下“ ISO8859_1'无效。解决这种情况的另一种方法是将charset更改为正确的值,然后再读取为字符串:

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