階段5 3.微服務項目【學成在線】_day04 頁面靜態化_14-頁面靜態化-數據模型-遠程請求接口

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

配置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的微服務,而後再啓動測試的方法!!!!





測試代碼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);

    }
}
相關文章
相關標籤/搜索