setting content type in rest assured

62.9k Views Asked by At

I'm trying to invoke a rest call using rest assured. My API accepts, "application/json" as content type and I need to set in the call. I set the content type as mentioned 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 response I get is "415" (indicates that "Unsupported media type ").

I tried invoking the same api using plain java code and it works. For some mysterious reason, I cudn't get it working 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);
    }
8

There are 8 best solutions below

0
On

I faced similar issue while working with rest-assured 2.7 version. I tried setting both the contentType and also accept to application/json but it 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 Content-Type header due to which the server is not able to differentiate between the media type and the rest of the request content and hence throwing the error 415 - "Unsupported media type".

0
On

Give a try given().contentType(ContentType.JSON).body(inputPayLoad.toString)

0
On

I was facing something similar and after some time we noticed the problem was actually coming from the server side. Please check your call on Postman and see if when it's triggered you need to change it from HTML to JSON. If you need to do that, the backend may need to force the response to be in JSON format by adding its content type. Even if it's encoded in JSON you're still may need to do that.

Thats the line of code we added:

header('Content-type:application/json;charset=utf-8');

.

  public function renderError($err){
   header('Content-type:application/json;charset=utf-8');
   echo json_encode(array(
       'success' => false,
       'err' => $err
   ));
}

And that's what was happening on the backend:

enter image description here

Hope that can help somehow. :)

0
On

This might possibly be the case with your test. Try this.

https://github.com/rest-assured/rest-assured/wiki/Usage#avoid-adding-the-charset-to-content-type-header-automatically

Avoid adding the charset to content-type header automatically

By default REST Assured adds the charset header automatically. To disable this completely you can configure the EncoderConfig like this:

RestAssured.config = RestAssured.config(config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false));
0
On

As mentioned in previous posts there is a method:

RequestSpecification.contentType(String value)

I did not work for me too. But after upgrade to the newest version (in this moment 2.9.0) it works. So please upgrade :)

1
On
import io.restassured.RestAssured;
import io.restassured.http.ContentType;

import static org.hamcrest.Matchers.is;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;

public class googleMapsGetLocation {
    @Test
    public void getLocation() {
        RestAssured.baseURI = "https://maps.googleapis.com";
        given().param("location", "-33.8670522,151.1957362")
            .param("radius", "500")
            .param("key", "AIzaSyAONLkrlUKcoW-oYeQjUo44y5rpME9DV0k").when()
            .get("/maps/api/place/nearbysearch/json").then().assertThat()
            .statusCode(200).and().contentType(ContentType.JSON)
            .body("results[0].name", is("Sydney"));
    }
}
3
On

For your First option can you please try adding this header too and sending the request?

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

1
On

Here is the complete POST example using CONTENT_TYPE as JSON.

import io.restassured.http.ContentType;

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