M
M
Multigame2018-05-13 14:53:28
C++ / C#
Multigame, 2018-05-13 14:53:28

How to set response encoding for HttpClient?

Good afternoon!
I send POST requests to the server with HttpClient. Request and response in win-1251 encoding, the response contains Cyrillic, which all turns into question marks. Tell me how to correctly specify the encoding of the received content (server response)?

using (var client = new HttpClient())
                 {
                    gate.addHeaders(client);
                    client.DefaultRequestHeaders.Pragma.Add(new NameValueHeaderValue("no-cache"));
                    var content = new StringContent(body, gate.getEncode(), gate.getMediaType()); // тело запроса
                    var result = await client.PostAsync(uri, content); // запрос
                    var str = await result.Content.ReadAsStringAsync();
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Fomin, 2018-05-13
@fomindp

Hello!
Here is the code that should solve the problem:

using (var client = new HttpClient())
{
  gate.addHeaders(client);
  client.DefaultRequestHeaders.Pragma.Add(new NameValueHeaderValue("no-cache"));
  var content = new StringContent(body, gate.getEncode(), gate.getMediaType()); // тело запроса
  var result = await client.PostAsync(uri, content); // запрос
  var buffer = await result.Content.ReadAsByteArrayAsync();
  var byteArray = buffer.ToArray();
  var responseString = Encoding.GetEncoding(1251).GetString(byteArray, 0, byteArray.Length);
}

S
Stanislav Makarov, 2018-05-13
@Nipheris

Accept Charset

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question