使用桌面应用程序中的RestTemplate消费服务时出现问题 [英] Issue When Consume Rest Service with RestTemplate in Desktop App

查看:176
本文介绍了使用桌面应用程序中的RestTemplate消费服务时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在桌面应用程序中使用RestTemplate消费服务时遇到问题,而在Web应用程序中使用时问题没有出现。

I have a problem when Consume Rest Service with RestTemplate in Desktop App whereas the problem doesn't appear when i use in Web app.

这是调试日志

15:30:40.448 [main] DEBUG o.s.web.client.RestTemplate - Reading [java.util.List] as "application/json" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@98adae2]
15:30:40.452 [main] DEBUG httpclient.wire.content - << "[{"name":"Indonesia","id":1},{"name":"AlaySia","id":2},{"name":"Autraliya","id":3}]"




线程main中的异常java.lang.ClassCastException:java .util.LinkedHashMap无法强制转换为com.mgm.domain.Country

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.mgm.domain.Country

这是我使用的代码。

 String url = "http://localhost:8080/mgm/country";
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(MediaType.APPLICATION_JSON);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(mediaTypes);
    HttpEntity<Country> httpEntity = new HttpEntity<Country>(null, headers);
    try {
        ResponseEntity<List> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, List.class);
        List<Country> countries = responseEntity.getBody();
        System.out.println(countries.get(0).getName());

    } catch (RestClientException exception) {
        exception.printStackTrace();
    }

当我将代码放入网络应用程序时,上面的代码不会出错。我使用Spring Rest MVC来提供JSON并将其与RestTemplate一起使用。

Code above doesn't give errors when i place it in web app. I use Spring Rest MVC to Provide JSON and Consume it with RestTemplate.

我认为当Jackson转换 java.util.LinkedHashMap时出现问题/ code>到国家。它似乎 countries.get(0)实际上有 LinkedHashMap 类型不是国家,当我调用 Country 之类的方法时会出现问题,例如 .getName()

I think there is a problem when Jackson Convert java.util.LinkedHashMap to Country . it Seems that countries.get(0) actually has LinkedHashMap type not Country and problem will appeared when i invoke one of Country methode like .getName()

推荐答案

尝试改为使用数组:

String url = "http://localhost:8080/mgm/country";
List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.APPLICATION_JSON);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(mediaTypes);
HttpEntity<Country> httpEntity = new HttpEntity<Country>(null, headers);
try {
    ResponseEntity<Country[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Country[].class);
    Country[] countries = responseEntity.getBody();
    System.out.println(countries[0].getName());

} catch (RestClientException exception) {
    exception.printStackTrace();
}

这篇关于使用桌面应用程序中的RestTemplate消费服务时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆