使用RestSharp设置’Content-Type’标头

我正在为RSS阅读服务建立一个客户端。 我正在使用RestSharp库与他们的API进行交互。

API声明:

创建或更新记录时,必须设置application / json; charset = utf-8作为Content-Type标头。

这就是我的代码:

RestRequest request = new RestRequest("/v2/starred_entries.json", Method.POST); request.AddHeader("Content-Type", "application/json; charset=utf-8"); request.RequestFormat = DataFormat.Json; request.AddParameter("starred_entries", id); //Pass the request to the RestSharp client Messagebox.Show(rest.ExecuteAsPost(request, "POST").Content); 

然而; 服务返回“错误415:请使用’Content-Type:application / json; charset = utf-8’标题。” 为什么RestSharp不通过标题?

我的博客上提供的解决方案未在RestSharp的1.02版本之外进行测试。 如果您针对我的解决方案的具体问题提交我的答案评论,我可以更新它。

 var client = new RestClient("http://www.example.com/where/else?key=value"); var request = new RestRequest(); request.Method = Method.POST; request.AddHeader("Accept", "application/json"); request.Parameters.Clear(); request.AddParameter("application/json", strJSONContent, ParameterType.RequestBody); var response = client.Execute(request); 

在版本105.2.3.0中,我可以通过这种方式解决问题:

 var client = new RestClient("https://www.example.com"); var request = new RestRequest("api/v1/records", Method.POST); request.AddJsonBody(new { id = 1, name = "record 1" }); var response = client.Execute(request); 

旧问题,但仍然是我的搜索的顶部 – 添加完整性。

虽然这有点旧:我遇到了同样的问题..似乎某些属性,如“内容类型”或“日期”不能作为参数添加,但在内部添加。 要改变“内容类型”的值,我必须更改序列化设置(尽管我没有使用它,因为我在之前序列化的主体中添加了一个json!)

 RestClient client = new RestClient(requURI); RestRequest request = new RestRequest(reqPath, method); request.JsonSerializer.ContentType = "application/json; charset=utf-8"; 

我一做到这一点,标题就出现了:

  System.Net Information: 0 : [5620] ConnectStream#61150033 - Header { Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml User-Agent: RestSharp 104.1.0.0 Content-Type: application/json; charset=utf-8 ... } 

你最有可能遇到这个问题: https : //github.com/restsharp/restsharp/issues/221你的问题有一个可行的解决方案@ http://itanex.blogspot.co.at/2012/02/restsharp-和先进的后requests.html

这是解决方案

http://restsharp.blogspot.ca/

创建具有相同名称属性的json对象并设置值(确保它们与post请求的名称值对类似)。

之后使用默认的httpclient。