I have the following code to submit a post http call:
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
);
The call is successfully reaching the server and it returns a 200 success code
ResponseEntity.ok().body("Successfully handled the request");
I keep getting the following error after the call is done
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')
I tried using RestTemplate with converters instead of the default one in org.springframework.web.client.
However, I still get the same error
A better idea would be to deserialize the response to String instead of Object as the response type.
Created a small demo.
Controller:
@RestController
@RequestMapping("demo")
public class DemoController {
@PostMapping
public ResponseEntity<String> demo() {
return ResponseEntity.ok().body("Successfully handled the request");
}
}
Main logic with RestTemplate:
public class Demo {
public static void main(String[] args) {
var restTemplate = new RestTemplate();
var response = restTemplate.exchange(
"http://localhost:8081/demo",
HttpMethod.POST,
null,
String.class
);
System.out.printf("Response Code: %s%n", response.getStatusCode());
System.out.printf("Response Body: %s%n", response.getBody());
}
}
Output:
Response Code: 200 OK
Response Body: Successfully handled the request
I'm assuming you're returning response with Header "ContentType" application/json, which makes HttpMessageConverterExtractor pick a json HttpMessageConverter to read the response, and your response body is not valid json, hence the exception. You should change the response Header "ContentType" to "text/plain" instead. And consider using ResponseEntity to accept the response instead of Response for better readability and maintainability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With