0

I'm trying to send json data with a REST POST request in Xamarin but no matter what i try I always get this error in response :

{ "message" : "Unexpected Content-Type 'application/x-www-form-urlencoded', expecting 'application/json'."}

I tested my request with this website : https://resttesttest.com/ and the response is ok with header set to "Content-Type", "application/json".

But within my code it's never working. I tried this method :

var request = new RestRequest("api/1/databases/{db}/collections/{coll}", Method.POST);
request.AddParameter("apiKey", Common.API_KEY);
request.AddUrlSegment("db", Common.DB_NAME);
request.AddUrlSegment("coll", collection);
request.AddHeader("Accept", "application/json");
request.AddParameter("application/json", JsonConvert.SerializeObject(objet), ParameterType.RequestBody);

And this one :

var request = new RestRequest("api/1/databases/{db}/collections/{coll}", Method.POST);
request.AddParameter("apiKey", Common.API_KEY);
request.AddUrlSegment("db", Common.DB_NAME);
request.AddUrlSegment("coll", collection);
request.AddHeader("content-type", "application/json; charset=utf-8");
if (objet != null)
    request.AddJsonBody(objet);

And many other but no mater what i do I always get the same response.

Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56
Rémi Hirtz
  • 113
  • 3
  • 14
  • 1
    `AddParameter` will add your parameter inside the request *body* in a `POST` request (using `application/x-www-form-urlencoded` as content-type). Where do you need your `apiKey`? – Federico Dipuma May 25 '17 at 10:50
  • I need to pass my `apiKey` as a query parameter to access my data throw mLab REST API. Here is an example: `https://api.mlab.com/api/1/databases?apiKey=2E81PUmPFI84t7UIc_5YdldAp1ruUPKye` – Rémi Hirtz May 25 '17 at 10:56
  • It's `Content-Type` not `content-type` – spender May 25 '17 at 10:56
  • @spender Header names are [case-insensitive](https://stackoverflow.com/questions/5258977/are-http-headers-case-sensitive) – Federico Dipuma May 25 '17 at 10:58
  • 1
    @FedericoDipuma Well, something learned today. Thanks. – spender May 25 '17 at 10:59

1 Answers1

1

If the request method is POST, AddParameter will add your parameter in the request body (if invoked using only two arguments).

If you need to put your parameter inside the query string you need to specify that explicitly:

request.AddParameter("apiKey", Common.API_KEY, ParameterType.QueryString);
// other segments omitted
request.AddJsonBody(objet);
Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56