RestSharp ignores response charset encoding

我们两清 提交于 2019-12-01 07:48:58

问题


I'm using RestSharp version 105.1.0 (.NET 4.5.1) to make a REST call to our own API. This API sends responses with the following header of particular interest: Content-Type: application/json; Charset=iso-8859-1. As you can see, the charset of this response is set to iso-8859-1.

I would expect that the response I get from RestSharp uses this encoding to decode the response content. However, when I look at the RestResponse.Content property, some characters display as �. As far as i know this means the wrong encoding was used. When I try decoding the RawBytes manually using the proper encoding, I do get the correct string.

I tried manually setting the iso-8859-1 Encoding property on the RestClient but to no avail.

How can I make sure the responses from RestSharp are decoded using the right encoding?

Example code:

// Setting the Encoding here does not change the result
var client = new RestClient(myApiUri) { Encoding = Encoding.GetEncoding("iso-8859-1") };
var request = new RestRequest(Method.GET);
var restResponse = client.Execute(request);
Console.WriteLine(restResponse.Content)
// Outputs content as string with wrong encoding
// some characters display as �

Thanks in advance!


回答1:


I also had this problem, to solve had to get the byte array that it brings in IRestResponse object and convert it to encode I want

var request = new RestRequest(Method.GET);
var restResponse = client.Execute(request);

Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
var result = encoding.GetString(response.RawBytes);
Console.WriteLine(result);


来源:https://stackoverflow.com/questions/37720731/restsharp-ignores-response-charset-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!