设置内容类型放心

我正试图用放心的方式调用rest电话。 我的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); } 

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

 RestAssured.given().contentType("application/json\r\n") 

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

尝试给出()。contentType(ContentType.JSON).body(inputPayLoad.toString)

以下是使用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(); } 

对于您的第一个选项,您可以尝试添加此标题并发送请求吗?

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

如前面的post所述,有一种方法:

RequestSpecification.contentType(String value)

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

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

这是我们添加的代码行:

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

这就是后端发生的事情:

在此处输入图像描述

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