无法解析restTemplate.exchange的响应

问题描述 投票:0回答:1

我有以下代码来提交http后调用

HttpHeaders headers = new HttpHeaders();
headers.set(TENANT_ID_HEADER, event.getTenantId());
HttpEntity<InputObj> requestEntity = new HttpEntity<>(inputObj, headers);
ResponseEntity<Object> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                Object.class
            );

调用已成功到达服务器并返回 200 成功代码

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

通话完成后我不断收到以下错误

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;
中的默认模板,但是我仍然遇到相同的错误

java spring http resttemplate
1个回答
0
投票

我假设您返回的响应带有标头“ContentType”application/json,这使得 HttpMessageConverterExtractor 选择一个 json HttpMessageConverter 来读取响应,并且您的响应正文不是有效的 json,因此出现异常。您应该将响应标头“ContentType”更改为“text/plain”。并考虑使用 ResponseEntity 来代替 Response 来接受响应,以获得更好的可读性和可维护性。

© www.soinside.com 2019 - 2024. All rights reserved.