Java 放心设置内容类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26976624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:36:16  来源:igfitidea点击:

setting content type in rest assured

javarest-assured

提问by TechRookie

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.

我正在尝试使用放心调用休息电话。我的 API 接受,"application/json"作为内容类型,我需要在调用中进行设置。我设置了下面提到的内容类型。

Option 1

选项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

选项 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 ").

我得到的响应是“415”(表示“不支持的媒体类型”)。

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.

我尝试使用普通的 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);
    }

回答by Anoop Philip

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

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

回答by Raghu Kiran

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

对于您的第一个选项,您能否也尝试添加此标头并发送请求?

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

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

回答by Samrat.K

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.

我在使用放心的 2.7 版本时遇到了类似的问题。我尝试设置 contentType 并接受 application/json 但它没有用。在末尾添加回车符和换行符,如下对我有用。

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

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

回答by Ziemowit Stolarczyk

As mentioned in previous posts there is a method:

正如之前的帖子中提到的,有一个方法:

RequestSpecification.contentType(String value)

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

我也没有为我工作。但是升级到最新版本(此时是 2.9.0)后,它可以工作了。所以请升级:)

回答by Nitin Pawar

Here is the Complete POST exmaple using CONTENT_TYPE as JSON.Hope it will help you.

这是使用 CONTENT_TYPE 作为 JSON 的完整 POST 示例。希望对您有所帮助。

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

回答by Francislainy Campos

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 backendmay need to force the response to be in JSONformat by adding its content type. Even if it's encoded in JSONyou're still may need to do that.

我遇到了类似的问题,一段时间后我们注意到问题实际上来自服务器端。请检查您对 Postman 的调用,看看是否需要在触发时将其从 HTML 更改为 JSON。如果您需要这样做,后端可能需要通过添加其内容类型来强制响应为 JSON格式。即使它是用 JSON 编码的,您仍然可能需要这样做。

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

希望能以某种方式提供帮助。:)

回答by Anil Jain

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