RestTemplate使用java.net.UnknownHostException 解决

更多内容请浏览本人博客

在使用RestTemplate 时,直接使用

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<QzhResult> responseEntity = restTemplate.getForEntity("http://MY-SERVER/token/{1}", String.class, "aa");

发现url只能填写项目地址,而不能填注册中心id,填id会爆如下错误:

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://{myserver:port}/Thingworx/Things/{...}/Services/findUser":
 {myserver}; nested exception is java.net.UnknownHostException: {myserver}
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:607)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
        at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)
        at spring.web.services.impl.AccountSerivceImpl.findUser(AccountSerivceImpl.java:115)
        at spring.web.controller.PageController.test(PageController.java:89)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)....

解决办法如下:
添加Javabean配置

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

注入RestTemplate:

    @Autowired
    RestTemplate restTemplate;//定义为私有可能会报错

使用:


    ResponseEntity<QzhResult> responseEntity = restTemplate.getForEntity("http://MY-SERVER/token/{1}", String.class, "aa");

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,329评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,052评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,905评论 18 399
  • 除了未来什么也别想 除了以后什么也遇不到 要不就这样吧 让炙热的炙热 燃烧的燃烧 灰烬的归于灰烬 我们来于尘土 也...
    苏子远阅读 2,472评论 0 0
  • 学生时代喜欢绘画,到现在十几年没有摸过画笔了,如今重新开始画画,做自己喜欢的事。
    流走的云阅读 2,701评论 0 1