阶段5 3.微服务项目【学成在线】_day04 页面静态化_14-页面静态化-数据模型-远程请求接口

okhttp的官方文档:

https://square.github.io/okhttp/

 github的地址

https://github.com/square/okhttp/

 

如何远程请求轮播图的DataUrl

之前已经添加过引用。

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

 


最终使用OkHttpClient

配置RestTemplate的Bean

 

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());
    }
}

 

使用RestTemplate

在Service里面注入就可以

测试类去测试RestTemplate





restTemplate里面有很多的方法

因为我们刚才写的DataUrl的接口是get的所以这里用getForEntity

responseType就是响应类型,这里我们用Map

使用getBody拿到具体的数据

测试的时候一定要先启动manage-cms的微服务,然后再启动测试的方法!!!!





测试代码

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);

    }
}

 

posted @ 2019-09-26 17:32  高山-景行  阅读(254)  评论(0编辑  收藏  举报