设置内容类型放心

Tec*_*kie 11 java rest-assured

我正试图用放心的方式调用休息电话.我的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());
Run Code Online (Sandbox Code Playgroud)

选项2

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

我得到的响应是"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);
    }
Run Code Online (Sandbox Code Playgroud)

Sam*_*t.K 11

在使用有保证的2.7版本时,我遇到了类似的问题.我尝试设置contentType并同时接受application/json,但它不起作用.最后添加了回车符和换行符,因为以下内容对我有用.

RestAssured.given().contentType("application/json\r\n")
Run Code Online (Sandbox Code Playgroud)

在Content-Type标头之后添加新行字符似乎缺少API,因为服务器无法区分媒体类型和其他请求内容,因此抛出错误415 - "不支持的媒体类型".


小智 7

这是使用 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();
}
Run Code Online (Sandbox Code Playgroud)


Ano*_*lip 4

试一下 given().contentType(ContentType.JSON).body(inputPayLoad.toString)