c# - RestSharp 不对请求进行 UTF-8 编码

标签 c# .net encoding utf-8 restsharp

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

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 友好的方式发送请求,这样她就不会混淆数据?

最佳答案

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

关于c# - RestSharp 不对请求进行 UTF-8 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29957654/

相关文章:

php - 将编码字符转换回原始字符 - PHP

c# - ApiHubFile Azure Function 绑定(bind)的动态输出文件名(一个驱动器、投递箱等)

C# - 在绑定(bind)中从 System.String 转换为 System.Nullable<Sytem.Int32> 时出现问题

.net - 在 menuitem WPF xaml 中创建分隔符

c++ - 如何将 UTF-8 std::string 转换为 UTF-16 std::wstring?

asp.net - 防止 ASP.NET 对输出中的字符串进行编码

c# - 有没有什么方法可以在不轮询的情况下在服务器中查找新消息?

c# - 为什么 Random.Next() 返回一个 int 而不是 uint?

c# - 如何生成测试数据?

c# - 枢轴重叠 WP 8.1 通用应用程序中的其他元素(并自动更改边距)