fakemeta
fakemeta

Reputation: 133

Invalid Charset in HTTP response

I'm writing a C# application for Windows Phone 8.1. The application sends a http request to a webpage with post data, however, it throws an exception when I copy the request content to a string.

Here is the code,

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);
    }
}

The error is,

"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."

Apparently the solution is to use GetByteArrayAsync instead of PostAsync (How to change the encoding of the HttpClient response), but this way I cannot submit post data.

Upvotes: 2

Views: 4087

Answers (2)

mqueirozcorreia
mqueirozcorreia

Reputation: 943

Some servers response can have invalid charsets, in this case 'ISO8859_1' is not valid. Another way to solve this situation is change the charset to the correct value, before reading as string:

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

Upvotes: 2

EZI
EZI

Reputation: 15354

Apparently the solution is to use GetByteArrayAsync instead of PostAsync

No you can use ReadAsByteArrayAsync method of HttpContent class

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

Upvotes: 4

Related Questions