zoukankan      html  css  js  c++  java
  • 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;
        }
        
    }
  • 相关阅读:
    查看自己的笔记本是否支持64位系统
    关闭445端口
    与postgis相关的一些常用的sql
    postgis 赋予postgresql空间数据库的能力
    ThreadLocal
    获取跨域请求的自定义的response headers
    java Bean的映射工具
    Java多线程学习
    (14)Spring Boot定时任务的使用【从零开始学Spring Boot】
    (13)处理静态资源(自定义资源映射)【从零开始学Spring Boot】
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/9203530.html
Copyright © 2011-2022 走看看