Setting the content type at rest

I try to call a call to rest, remaining confident. My API accepts "application/json" as a content type, and I need to set it in a call. I set the content type as below.

Option 1

 Response resp1 = given().log().all().header("Content-Type","application/json") .body(inputPayLoad).when().post(addUserUrl); System.out.println("Status code - " +resp1.getStatusCode()); 

Option 2

 Response resp1 = given().log().all().contentType("application/json") .body(inputPayLoad).when().post(addUserUrl); 

The answer I get is "415" (indicates "Unsupported media type").

I tried using the same api using simple Java code and it works. For some mysterious reason, I don't get it through RA.

  HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(addUserUrl); StringEntity input = new StringEntity(inputPayLoad); input.setContentType("application/json"); post.setEntity(input); HttpResponse response = client.execute(post); System.out.println(response.getEntity().getContent()); /* BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println("Output -- " +line); } 
+7
java rest-assured
source share
5 answers

I encountered a similar problem while working with version 2.7 for the rest. I tried installing both contentType and accepting the / json application, but that didn't work. Adding carriage feed and new line characters at the end as the following worked for me.

 RestAssured.given().contentType("application/json\r\n") 

The API seems to be missing to add new line characters after the Content-Type header, which is why the server cannot distinguish between the media type and the rest of the request content and, therefore, throw error 415 - "Unsupported media type".

+7
source share

Try it given (). CONTENTTYPE (ContentType.JSON) .Body (inputPayLoad.toString)

+1
source share

In your first option, can you try adding this header and submitting a request?

.header("Accept","application/json")

0
source share

As mentioned in previous posts, there is a way:

RequestSpecification.contentType(String value)

I did not work for me either. But after switching to the new version (at this moment 2.9.0) it works. So please update :)

0
source share

Here is a complete POST example using CONTENT_TYPE as JSON.Hope, this will help you.

 RequestSpecification request=new RequestSpecBuilder().build(); ResponseSpecification response=new ResponseSpecBuilder().build(); @Test public void test(){ User user=new User(); given() .spec(request) .contentType(ContentType.JSON) .body(user) .post(API_ENDPOINT) .then() .statusCode(200).log().all(); } 
0
source share

All Articles