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 or updating a record you must set
application/json;charset=utf-8
as theContent-Type
header.
This is what my code looks like:
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);
However; the service is returning an error
Error 415: Please use the 'Content-Type: application/json; charset=utf-8' header
Why isn't RestSharp passing the header?
Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.
It's better to specify the Json data body. var client = new RestClient("URL"); var request = new RestRequest("Resources",Method. POST); request. RequestFormat = RestSharp.
The request body is a type of parameter. To add one, you can do one of these... req. AddBody(body); req.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With