Android for Spring - 无法提取响应:没有为响应类型找到合适的HttpMessageConverter

时间:2014-08-05 14:39:17

标签: java android spring robospice spring-android

我尝试使用Spring for Android从REST服务中检索一些数据。 但是,我遇到了问题。我也使用Robospice - 因此有一个像这样的方法:

 public FunkyThingsList loadDataFromNetwork() throws Exception {
        String baseURI =context.getResources().getString(R.string.baseWebServiceURI);
                String uri = baseURI + "/FunkyThings/date/" + dateToLookUp.toString("yyyy-MM-dd");
        RestTemplate restTemplate = getRestTemplate();
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept( Arrays.asList(MediaType.APPLICATION_JSON));
        HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
        headers.setAuthorization(authHeader);

        // Create the request body as a MultiValueMap
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        HttpMessageConverter<String> stringConverter = new StringHttpMessageConverter();
        FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
        List<HttpMessageConverter<?>> msgConverters = restTemplate.getMessageConverters();
        msgConverters.add(formConverter);
        msgConverters.add(stringConverter);
        restTemplate.setMessageConverters(msgConverters);

        HttpEntity<?> httpEntity = new HttpEntity<Object>(map, headers);
        final ResponseEntity<FunkyThingsList> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity,FunkyThingsList.class);

        return responseEntity.getBody();
    }

不幸的是,这不起作用。我引发了以下异常:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.MyProject.DataClassPojos.RoboSpiceArrayLists.FunkyThingsList] and content type [application/json;charset=utf-8]

现在基于我的谷歌搜索我觉得我需要添加一个消息转换器。我只是不确定我需要哪个消息转换器,或者我添加它的位置?

2 个答案:

答案 0 :(得分:1)

对于默认的JSON HttpMessageConverter,您需要在类路径中添加Jackson 1或Jackson 2。

否则,您可以添加一些其他JSON库并编写自己的HttpMessageConverter来进行反序列化。您将其添加到RestTemplate。您可以使用构造函数或this method

答案 1 :(得分:0)

如果您正在关注Spring for Android教程并得到相同的错误 - 这可能会有所帮助:

在您的MainActivity.java中:

...
RestTemplate restTemplate = new RestTemplate();
MappingJacksonHttpMessageConverter converter = new
MappingJacksonHttpMessageConverter();    
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML));
restTemplate.getMessageConverters().add(converter);

在调用中使用转换器并将其配置为使用TEXT_HTML作为媒体类型,然后使用转换器的实例。

此教程也有点过时,因此请在build.gradle中使用最新版本suggested here

dependencies{
 //Spring Framework for REST calls and Jackson for JSON processing
 compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3'

 compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1.3'
}
repositories {
 maven {
    url 'https://repo.spring.io/libs-milestone'
 }
}