我正在尝试使用Spring for Android 来解析 XML 响应。我过去成功地实现了Spring来解析 JSON 响应,但由于某种原因我遇到了 XML 问题。
我下载了Simple jar 并将其添加到我的构建路径中。我没有收到任何编译错误,但是当我运行它时,我遇到了问题。这是我的代码:
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());
}
运行此代码时出现的错误如下:
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)
此行引发错误:ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
只是为了测试,我使用了这个:restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
从我的消息转换器中,我得到了作为字符串的正确响应。
有任何想法吗?