Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set 'Content-Type' header using RestSharp

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 the Content-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?

like image 605
Shane Gowland Avatar asked Jul 23 '13 15:07

Shane Gowland


People also ask

Does RestSharp use HttpClient?

Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.

How do I send a post request on RestSharp?

It's better to specify the Json data body. var client = new RestClient("URL"); var request = new RestRequest("Resources",Method. POST); request. RequestFormat = RestSharp.

How do I request a RestSharp body?

The request body is a type of parameter. To add one, you can do one of these... req. AddBody(body); req.


2 Answers

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); 
like image 125
Itanex Avatar answered Sep 18 '22 11:09

Itanex


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.

like image 40
Tom Elmore Avatar answered Sep 18 '22 11:09

Tom Elmore