RestTemplate请求http接口

在做页面静态化的时候用到,就来记录以下。

SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层使用第三方的http客户端工具实现http 的 请求,常用的http客户端工具有Apache HttpClient、OkHttpClient等,这里使用OkHttpClient完成http请求。
简单的说RestTemplate其实就是一个http的客户端。

使用步骤:

第一步:添加依赖

<dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
</dependency>

第二步:配置RestTemplate
在SpringBoot启动类中配置 RestTemplate

public class ManageCmsApplication {
    public static void main(String[] args) {
        SpringApplication.run(ManageCmsApplication.class);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }
    
}

测试:

@Autowired
    RestTemplate restTemplate;

    @Test
    public void testRestTemplate(){
        ResponseEntity<Map> forEntity = restTemplate.getForEntity("http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f", Map.class);
        Map body = forEntity.getBody();
        System.out.println(body);
    }

出错:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for “http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f”: Failed to connect to localhost/0:0:0:0:0:0:0:1:31001; nested exception is java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:31001

Caused by: java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:31001

重新启动SpringBoot启动类,再启动,后解决。。。无奈。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值