Reputation: 7841
When I am posting form request, spring is adding charset like application/x-www-form-urlencoded; charset=UTF-8
which causing problem to consume restful service. How can I remove the charset from RestTemplate to so the content-type is exactly application/x-www-form-urlencoded
?
Upvotes: 3
Views: 2425
Reputation: 738
I had the same problem. I solved it by removing the charset from the contenttype in the header after it was added.
class MyFormHttpMessageConverter extends FormHttpMessageConverter {
@Override
public void write(final MultiValueMap<String, ?> map, final MediaType contentType, final HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
super.write(map, contentType, outputMessage);
HttpHeaders headers = outputMessage.getHeaders();
MediaType mediaType = headers.getContentType();
if(Objects.nonNull(mediaType) && MapUtils.isNotEmpty(mediaType.getParameters())){
Map<String, String> filteredParams = mediaType.getParameters()
.entrySet()
.stream()
.filter(entry -> !entry.getKey().equals("charset"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
headers.setContentType(new MediaType(mediaType, filteredParams));
}
}
}
Upvotes: 2
Reputation: 26094
FormHttpMessageConverter
makes a lot of validations to make sure you are using a MediaType with a valid charset. I would try either subclassing it and registering a new converter (there are a lot of private methods though), or converting your MultiValueMap
to String payload manually (StringHttpMessageConverter
is a lot less restrictive about Media Types)
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<String> entity = new HttpEntity<>("param1=value1", headers);
String result = restTemplate.postForObject( url, entity, String.class);
Upvotes: 4