设置内容类型'使用RestSharp的标头

时间:2013-07-23 15:51:20

标签: c# http-headers restsharp

我正在为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不通过标题?

6 个答案:

答案 0 :(得分:52)

my blog上提供的解决方案未在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);

答案 1 :(得分:30)

在版本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);

旧问题,但仍然是我搜索的首要问题 - 添加完整性。

答案 2 :(得分:9)

虽然这有点旧:我遇到了同样的问题..似乎某些属性如“content-type”或“date”不能作为参数添加但是在内部添加。要改变“内容类型”的值,我必须更改序列化设置(尽管我没有使用它,因为我之前在序列化中添加了一个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
  ...
 }

答案 3 :(得分:3)

答案 4 :(得分:0)

request.XmlSerializer = new DotNetXmlSerializer();
            request.Parameters.Clear();
            request.AddParameter(new Parameter()
            {
                ContentType = "application/xml",
                Name = "application/xml",
                Type = ParameterType.RequestBody,
                Value = request.XmlSerializer.Serialize(deleteUserQuery.UserDelRqHeader)
            });
            request.AddHeader("Accept", "application/xml");

答案 5 :(得分:-4)

这是解决方案

http://restsharp.blogspot.ca/

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

之后使用默认的httpclient。