RestSharp忽略响应字符集编码 [英] RestSharp ignores response charset encoding

查看:195
本文介绍了RestSharp忽略响应字符集编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RestSharp版本105.1.0(.NET 4.5.1)对我们自己的API进行REST调用。该API发送带有以下特别感兴趣的标头的响应: Content-Type:application / json; Charset = iso-8859-1 。如您所见,此响应的字符集设置为iso-8859-1。

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.

我希望我从RestSharp获得的响应使用此编码来解码响应内容。但是,当我查看 RestResponse.Content 属性时,某些字符显示为``。据我所知,这意味着使用了错误的编码。当我尝试使用正确的编码手动解码 RawBytes 时,我确实获得了正确的字符串。

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.

我手动尝试过在 RestClient 上设置iso-8859-1 Encoding 属性,但无济于事。

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

如何确保使用正确的编码对RestSharp的响应进行解码?

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

示例代码:

// 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 �

预先感谢!

推荐答案

我也遇到了这个问题,解决方案必须获取它带入IRestResponse对象的字节数组并将其转换为我想要的编码

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

这篇关于RestSharp忽略响应字符集编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆