21

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);
    }
Anirudh
  • 2,286
  • 4
  • 38
  • 64
TechRookie
  • 211
  • 1
  • 2
  • 7
  • Would it be possible to compare the request headers from your 2 first examples to request headers from the last example? – spg Nov 17 '14 at 18:05
  • Option 1 : Request method: POST Request path: http://10.75.43.46:7001/supplierapp-war/pim/addUser Request params: Query params: Form params: Path params: Headers: Content-Type=application/json Cookies: Option 2 : Request method: POST Request path: http://10.75.43.46:7001/supplierapp-war/pim/addUser Request params: Query params: Form params: Path params: Headers: Content-Type=application/json Cookies: – TechRookie Nov 19 '14 at 13:35
  • Request sent by HttpClient : Content Type : Content-Type: application/json Content Length : 203 Content : java.io.ByteArrayInputStream@646bfe00 content Encoding : null Note : I used following snippet to get header info from httpClient. System.out.println("Content Type : " +input.getContentType()); System.out.println("Content Length : " +input.getContentLength()); System.out.println("Content : " +input.getContent()); System.out.println("content Encoding : "+input.getContentEncoding()); – TechRookie Nov 19 '14 at 13:36
  • Hmm that really ought to work. Try upgrading to the latest version. – Johan Nov 23 '14 at 16:41

8 Answers8

14

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".

Samrat.K
  • 141
  • 1
  • 5
8

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();
}
Skippy le Grand Gourou
  • 6,976
  • 4
  • 60
  • 76
Nitin Pawar
  • 1,634
  • 19
  • 14
4

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

Michu93
  • 5,058
  • 7
  • 47
  • 80
Anoop Philip
  • 971
  • 2
  • 11
  • 19
1

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));
RuntimeException
  • 1,593
  • 2
  • 22
  • 31
0

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 :)

Ziemowit Stolarczyk
  • 1,014
  • 2
  • 11
  • 26
0

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. :)

Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81
0
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"));
    }
}
Anil Jain
  • 57
  • 3
  • 2
    While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context. – Robert Columbia Oct 29 '18 at 16:10
-1

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

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

Raghu Kiran
  • 2,347
  • 1
  • 15
  • 11