【问题标题】:Spring Resful Client with RestTemplate带有 RestTemplate 的 Spring Resful 客户端
【发布时间】:2016-03-30 08:36:46
【问题描述】:

我正在使用 RestTemplate 类来获取所有用户,但是当我在客户端中运行 Main 时出现错误,我不知道为什么?

线程“主”java.lang.ClassCastException 中的异常: java.util.LinkedHashMap 不能转换为 edu.java.spring.service.user.model.User 在 edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:33)

这里文件RestClientTest.java

public class RestClientTest {

    public static void main(String[] args) throws IOException{
        List<User> users = getUsers();
        for (int i = 0; i < users.size(); i++) {
            System.out.println("Rest Response" + loadUser(users.get(i).getUserName()));
        }

    }
    public static List<User> getUsers(){
        String uri = new String("http://localhost:8080/rest/user/list");
        RestTemplate rt = new RestTemplate();
        return (List<User>) rt.getForObject(uri,List.class);
    }

    public static String loadUser(String username) throws IOException {
        String url = "http://localhost:8080/rest/user/json/" + username;

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/json");
        InputStream stream = con.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(stream));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();

    }

这里文件UserRestServiceController.java

   @Controller
public class UserRestServiceController {
    @Autowired
    public  UserDao userDao;
    @Autowired
    public View jsonTemplate;
    @RequestMapping(value = "/rest/user/list", produces = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.GET)
    public @ResponseBody List<User> getUsers(){
        return userDao.listUsers();
    }
    @RequestMapping(value="/rest/user/json/{username}")
    public ModelAndView loadUser(@PathVariable("username")String name){
        return new ModelAndView(jsonTemplate,"data",userDao.loadUser(name));
    }

【问题讨论】:

  • 第 33 行到底是哪一行?
  • @dunni,函数声明。 System.out.println("Rest Response" + loadUser(users.get(i).getUserName()));
  • 那你能不能发一下控制器,映射到“localhost:8080/rest/user/json”+用户名?
  • @dunni,我的帖子上有后控制器
  • 为什么从 loadUser 方法返回一个 ModelAndView 实例?只需返回 User 对象并添加 ResponseBody 注释,就像在 getUsers 方法中一样。这应该有效。

标签: spring resttemplate


【解决方案1】:

我相信以下方法没有像您期望的那样返回:

rt.getForObject(uri,List.class);

看看这个问题,因为它还可以帮助您解决错误。 ClassCastException: RestTemplate returning List instead of List

【讨论】:

  • rt.getForObject(uri,User[].class)替换rt.getForObject(uri,List.class)
猜你喜欢
  • 2014-05-16
  • 2016-07-17
  • 2023-03-23
  • 1970-01-01
  • 2019-07-06
  • 2016-07-16
  • 2018-05-03
  • 2021-09-10
  • 2017-12-31
相关资源
最近更新 更多