20

安心を使用して休憩呼び出しを呼び出そうとしています。私の API は"application/json"コンテンツ タイプとして受け入れ、呼び出しで設定する必要があります。以下のようにコンテンツタイプを設定しました。

オプション1

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

オプション 2

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

私が得る応答は「415」です(「サポートされていないメディアタイプ」を示します)。

プレーンな Java コードを使用して同じ API を呼び出してみましたが、動作します。なんらかの不思議な理由で、私は 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);
    }
4

8 に答える 8

13

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

于 2016-02-18T12:03:07.060 に答える
8

CONTENT_TYPE を JSON として使用した完全な POST の例を次に示します。

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();
}
于 2017-03-28T06:23:35.913 に答える
-1

最初のオプションとして、このヘッダーも追加してリクエストを送信してみてください。

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

于 2015-10-30T06:29:52.337 に答える