okhttp的官方文档:java
https://square.github.io/okhttp/git
github的地址github
https://github.com/square/okhttp/web
如何远程请求轮播图的DataUrl
spring
以前已经添加过引用。api
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
最终使用OkHttpClient
dom
package com.xuecheng.manage_cms; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EntityScan("com.xuecheng.framework.domain.cms")//扫描实体类 @ComponentScan(basePackages={"com.xuecheng.api"})//扫描接口 @ComponentScan(basePackages={"com.xuecheng.framework"})//扫描common包下的类 @ComponentScan(basePackages={"com.xuecheng.manage_cms"})//扫描本项目下的全部类 public class ManageCmsApplication { public static void main(String[] args) { SpringApplication.run(ManageCmsApplication.class,args); } @Bean public RestTemplate restTemplate(){ return new RestTemplate(new OkHttp3ClientHttpRequestFactory()); } }
在Service里面注入就能够微服务
restTemplate里面有不少的方法
由于咱们刚才写的DataUrl的接口是get的因此这里用getForEntity
responseType就是响应类型,这里咱们用Map
使用getBody拿到具体的数据
测试
测试的时候必定要先启动manage-cms的微服务,而后再启动测试的方法!!!!
测试代码spa
package com.xuecheng.manage_cms; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; import java.util.Map; @SpringBootTest @RunWith(SpringRunner.class) public class RestTemplateTest { @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); } }