【问题标题】:RestSharp doesn't UTF-8 Encode the RequestRestSharp 不对请求进行 UTF-8 编码
【发布时间】:2015-07-09 13:27:23
【问题描述】:

我正在尝试使用一个单独的参数发布请求,例如:

var client = new RestClient("http://www.fluff.com");
var request = new RestRequest("whatever", Method.POST);
request.AddParameter("param", "Оксана");
client.Execute(request);

这会导致以下请求,注意一堆编码的问号:

POST http://www.fluff.com/whatever HTTP/1.1
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.0.1.0
Content-Type: application/x-www-form-urlencoded
Host: www.fluff.com
Content-Length: 24
Accept-Encoding: gzip, deflate

param=%3F%3F%3F%3F%3F%3F

想象一下接收者收到这些问号时的悲伤......

如何让 RestSharp 将正文正确编码为 UTF-8,或者如何以对 RestSharp 友好的方式发送请求,以免数据出现乱码?

【问题讨论】:

  • 你考虑过用 HttpClient 代替 RestSharp 吗? PostAsJsonAsync 让这一切变得非常简单。

标签: c# .net encoding utf-8 restsharp


【解决方案1】:

Christer,这是Content-Type: application/x-www-form-urlencoded 的标准编码,默认使用 ISO-8859-1。如果您特别想告诉服务器期待 UTF-8,您可以在末尾添加; charset=UTF-8 Content-Type: application/x-www-form-urlencoded ; charset=UTF-8。但是,您有责任确保您发布的数据真正以 UTF-8 编码。

或者如果你想在“application/json”中做,你可以这样设置内容类型(我从http://itanex.blogspot.com/2012/02/restsharp-and-advanced-post-requests.html得到这个):

request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", strJSONContent, ParameterType.RequestBody);

你也可以使用multipart/form-data:<form action="YOUR_ACTION_NAME_HERE" method="post" enctype="multipart/form-data">

【讨论】:

  • “如何让 RestSharp 将正文正确编码为 UTF-8,或者如何以 RestSharp 友好的方式发送请求,以免她的数据出现乱码?”如何设置 RestSharp 以便“内容类型:应用程序/json;charset=utf-8”。 RestSharp 覆盖了我设置内容类型的尝试。这是否使我的问题更清楚?问候
  • 是的,我明白你在说什么,但我很确定 RestSharp(用于 RESTful 调用的库)能够为我做到这一点。我自己编写了这些类型的库来处理这个问题,在我们当前的项目中,我们有另一个库可以自动处理这个问题,但是由于 RestSharp 是如此轻量级和漂亮,我想使用它。我现在面临的问题是 RestSharp 不允许我只通过指定标题来设置内容类型。它覆盖了我设置它的尝试。
  • 我想我发现了别的东西。您可能还必须在 AddParameter 调用中指定编码:request.AddParameter("application/x-www-form-urlencoded ; charset=UTF-8", paramName, paramValue);
  • 查看更新后的答案以及我从itanex.blogspot.com/2012/02/… 获得的代码。这可能正是您正在寻找的。​​span>
  • 如果你想要JSON,你可以使用request.AddJsonBody()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 2011-11-19
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多