• spring boot单元测试之RestTemplate(二)


    上篇博客中,简单介绍了RestTemplate,只是用到了单元测试环节,如果在正式开发环境使用RestTemplate调用远程接口,还有一些配置要做。

    一、配置类

    由于Spring boot没有对RestTemplate做自动配置,所以我们需要写一个配置类引入RestTemplate。

    @Configuration
    public class RestTemplateConfig {
        @Bean
        public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
            return new RestTemplate(factory);
        }
    
        @Bean
        public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
            SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            factory.setReadTimeout(5000);//单位为ms
            factory.setConnectTimeout(5000);//单位为ms
            return factory;
        }
    }

    二、工具类

    在实际开发过程中,可能对于调用远程接口有多种参数情况,因此写了一个工具类用来支持。

    RestTemplate功能非常强大,Post请求的时候特别要注意,body参数必须为MultiValueMap类型。

    @Service
    public class RestTemplateService {
        @Autowired
        private RestTemplate restTemplate;
    
        /**
         * 实测可用
         */
        public JSONObject doGet(String url) {
            JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
            return json;
        }
    
        /**
         * 实测可用
         */
        public JSONObject doGet(String url, HttpHeaders headers) {
            HttpEntity<String> entity = new HttpEntity<>(null, headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class);
            return exchange.getBody();
        }
    
        /**
         * 实测可用,body参数必须为MultiValueMap类型
         */
        public JSONObject doPost(String url, MultiValueMap<String, Object> param) {
            JSONObject json = restTemplate.postForEntity(url, param, JSONObject.class).getBody();
            return json;
        }
    
        /**
         * 实测可用,body参数必须为MultiValueMap类型
         */
        public JSONObject doPost(String url, MultiValueMap<String, Object> params, HttpHeaders headers) {
            JSONObject json = restTemplate.postForObject(url, new HttpEntity<>(params, headers), JSONObject.class);
            return json;
        }
        
    }
  • 相关阅读:
    CentOS 6.4 x64 zabbix 2.2.2 编译安装
    Monitorix 监控 安装配置
    CentOS 6.4 x64 Percona-Server-5.6.15 源码安装
    CentOS 6.4 x64 安装 配置 Redmine 2.4.1
    ActiviMQ的基本使用
    Java内存 模型理解
    线程池的两种创建方式及区别
    线程创建的三种方式及区别
    Spring cloud 之Ribbon(二)负载均衡原理
    Spring cloud 之Ribbon(一)基本使用
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/9203530.html
Copyright © 2020-2023  润新知