springmvc中restTemplate的使用

这篇博客只是记录,供自己参考使用
SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层可以使用第三方的http客户端工具实现http 的 请求
1.添加依赖

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

2.配置RestTemplate,最好就在启动的时候配置,方便我们使用

@SpringBootApplication
public class ManageCmsApplication {
    public static void main(String[] args){
        SpringApplication.run(ManageCmsApplication.class);
    }
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }
}

3.远程调用进行访问,当然restTemplate的功能非常强大,可以使用不同的请求进行访问,这里就不一一列举
访问远程地址,并将得到的参数封装为Map对象

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

猜你喜欢

转载自blog.csdn.net/weixin_43794897/article/details/85109292