Vlad Kudryavtsev Vlad Kudryavtsev - 1 month ago 38
reST (reStructuredText) Question

Spring RestTemplate throws InvalidMediaTypeException

I am new to Spring Rest,I've tried to fetch xml from webservice, but it's throwing InvalidMediaTypeException after the execution below code:

restTemplate.getForObject("http://www.dictionaryapi.com/api/v1/references/learners/xml/{word}?key={key}",String.class,uriVariables);


The WebService returns xml document, and I thought firstly that it could be the problem, but another WebService (that url doesn't contain 'xml' as path) works great.

Stacktrace:

Exception in thread "main" org.springframework.http.InvalidMediaTypeException: Invalid mime type "xml": does not contain '/'
at org.springframework.http.MediaType.parseMediaType(MediaType.java:385)
at org.springframework.http.HttpHeaders.getContentType(HttpHeaders.java:722)
at org.springframework.web.client.HttpMessageConverterExtractor.getContentType(HttpMessageConverterExtractor.java:114)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:85)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:835)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:819)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:599)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:384)


So how can I exchange data with WebServices, that contain word "xml" in their url path.

Answer

The problem here is that service is returning the Response to your query with a messed-up Content-Type, specifically xml. You need to configure Spring to handle that because sane people (and services) use application/xml instead. Check out this answer for custom MediaType settings.