Reputation: 61
I am using restTemplate to consume a service.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity request = new HttpEntity(countryRequest, headers);
CountryResponse response = restTemplate.postForObject(countryURL, request, CountryResponse.class);
countryRequest
is a object of a POJO with just a string field code
.
restTemplate
has jackson2HttpMessageConverter
and FormHttpMessageConverter
in messageConverters
.
I am getting the following exception :
org.springframework.web.client.RestClientException:
Could not write request: no suitable HttpMessageConverter found for request type [CountryRequest] and content type [application/x-www-form-urlencoded]
But if I use MultiValueMap
instead of CountryRequest
, I got the 200 response:
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add(code, "usa");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(map, headers);
Is there any way to replace the MultiValueMap
approach here?
Upvotes: 0
Views: 1110
Reputation: 3191
There is two main kinds of request serialization: as usual FORM data or as JSON object. Form Data is simplest and oldest way which sends a simple key-value pairs of strings in POST payload. But when you need to send some object with nested properties or some list or even map then it becomes a problem. That's why everybody tries to use a JSON format which can be more easily deserialized into POJO object. And this is a de facto standard for modern web.
So in your case for some reason RestTemplate
tries to serialize the CountryRequest
but it don't know how to serialize it into FORM data.
Try to replace the request
with a pojo that you are sending:
CountryRequest request = new CountryRequest();
CountryResponse response = restTemplate.postForObject(countryURL, request, CountryResponse.class);
Then RestTemplate tries to serialize the CountryRequest
into JSON (which is default behavior).
Upvotes: 2