okhttp的官方文档:

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

 github的地址

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

 

如何远程请求轮播图的DataUrl

之前已经添加过引用。

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

 


最终使用OkHttpClient

 

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

    }
}

 

相关文章:

  • 2021-06-06
  • 2022-01-09
  • 2021-10-25
  • 2022-01-20
  • 2021-06-15
  • 2021-09-22
  • 2022-02-21
  • 2021-06-16
猜你喜欢
  • 2021-08-16
  • 2021-06-02
  • 2021-09-11
  • 2022-01-07
  • 2021-12-23
  • 2022-02-15
  • 2022-01-18
相关资源
相似解决方案