2015-04-04 375 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();