spring 无法解析restTemplate.exchange的响应

4urapxun  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(251)

我有下面的代码来提交一个post http调用

  1. HttpHeaders headers = new HttpHeaders();
  2. headers.set(TENANT_ID_HEADER, event.getTenantId());
  3. HttpEntity<InputObj> requestEntity = new HttpEntity<>(inputObj, headers);
  4. ResponseEntity<Object> responseEntity = restTemplate.exchange(
  5. url,
  6. HttpMethod.POST,
  7. requestEntity,
  8. Object.class
  9. );

字符串
调用成功到达服务器,并返回200成功代码

  1. ResponseEntity.ok().body("Successfully handled the request");


在调用完成后,我一直收到以下错误

  1. Exception while performing api call with message : Error while extracting response for type [class java.lang.Object] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'Successfully': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Successfully': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')


我尝试使用我自己的RestTemplate与转换器,而不是默认的org.springframework.web.client;,但我仍然得到相同的错误

p8h8hvxi

p8h8hvxi1#

我假设你返回的响应头为“ContentType”application/json,这使得HttpMessageConverterExtractor选择一个json HttpMessageConverter来读取响应,而你的响应体不是有效的json,因此出现了异常。你应该将响应头“ContentType”改为“text/plain”。为了更好的可读性和可维护性,考虑使用ResponseEntity来接受响应。

相关问题