Set 'Content-Type' header using RestSharp

后端 未结 5 994
眼角桃花
眼角桃花 2020-12-08 19:39

I\'m building a client for an RSS reading service. I\'m using the RestSharp library to interact with their API.

The API states:

When creating

相关标签:
5条回答
  • 2020-12-08 19:44

    Here is the solution

    http://restsharp.blogspot.ca/

    Create a json object with same name properties and set the values (Make sure they are similar to those of name value pair for post request.)

    After that use default httpclient.

    0 讨论(0)
  • 2020-12-08 19:49

    In version 105.2.3.0 I can solve the problem this way:

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

    Old question but still top of my search - adding for completeness.

    0 讨论(0)
  • 2020-12-08 19:51

    Although this is a bit old: I ran into the same problem.. seems some attributes such as "content-type" or "date" cannot be added as parameter but are added internally. To alter the value of "content-type" I had to change the serialzer setting (altough I didn`t use it because I added a json in the body that was serialized before!)

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

    as soon as I did this the header showed up as intended:

     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
      ...
     }
    
    0 讨论(0)
  • 2020-12-08 19:56

    The solution provided on my blog is not tested beyond version 1.02 of RestSharp. If you submit a comment on my answer with your specific issue with my solution, I can update it.

    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);
    
    0 讨论(0)
  • 2020-12-08 19:57

    You most probably run into this problem: https://github.com/restsharp/restsharp/issues/221 There is a working solution to your problem @ http://itanex.blogspot.co.at/2012/02/restsharp-and-advanced-post-requests.html

    0 讨论(0)
提交回复
热议问题