I’m trying to using Spring for Android to parse an XML response. I’ve successfully implemented Spring in the past to parse JSON responses, but I’m running into problems with XML for some reason.
I downloaded and added the Simple jar to my build path. I don’t get any compilation errors, but when I run it, I get problems. Here is my code:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new MediaType("text","xml")));
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
String url = "MyURL";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());
try{
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
Log.d(TAG, "response - " + responseEntity.getBody());
}catch(HttpMessageNotReadableException e){
Log.d(TAG, "message " + e.getMessage());
}
The error I get when I run this code is the following:
02-11 16:49:28.905: E/AndroidRuntime(5454): FATAL EXCEPTION: Thread-126
02-11 16:49:28.905: E/AndroidRuntime(5454): org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [java.lang.String]
02-11 16:49:28.905: E/AndroidRuntime(5454): at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:632)
02-11 16:49:28.905: E/AndroidRuntime(5454): at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:473)
02-11 16:49:28.905: E/AndroidRuntime(5454): at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:438)
02-11 16:49:28.905: E/AndroidRuntime(5454): at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:414)
02-11 16:49:28.905: E/AndroidRuntime(5454): at com.rounded.rrbcataloguelibrary.RRBCatalogueActivity.getCategories(RRBCatalogueActivity.java:337)
02-11 16:49:28.905: E/AndroidRuntime(5454): at com.rounded.rrbcataloguelibrary.RRBCatalogueActivity$7.run(RRBCatalogueActivity.java:395)
02-11 16:49:28.905: E/AndroidRuntime(5454): at java.lang.Thread.run(Thread.java:856)
The error is thrown on this line: ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
Just to test, I used this: restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); from my message converter and I got the proper response as a string.
Any ideas?
It seems like you’re trying to set the accept headers as the body of the message. That’s probably not what you want…
The ResponseEntity should wrap an object that’s XML-serializable (looking at the converter code, seems like it’s looking for the @Root annotation). Anyway, with Spring you (generally) don’t have to worry about setting the accept/content-type headers directly, since those will be set by the MessageConverters.