springboot (RestTemplate)网络请求封装

配置类

package com.gzkj.admin.config;


import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 
 *
 * @author CJJ
 * @version 1.0
 * @createDate 2019/09/05 16:13
 */
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})
public class RestfulConfig {

    /* 连接池的最大连接数默认为0 */
    @Value("${remote.maxTotalConnect:1}")
    private int maxTotalConnect;
    /* 单个主机的最大连接数 */
    @Value("${remote.maxConnectPerRoute:200}")
    private int maxConnectPerRoute;
    /* 连接超时默认2s */
    @Value("${remote.connectTimeout:120000}")
    private int connectTimeout;
    /* 读取超时默认30s */
    @Value("${remote.readTimeout:180000}")
    private int readTimeout;

    //创建HTTP客户端工厂
    private ClientHttpRequestFactory createFactory() {
        if (this.maxTotalConnect <= 0) {
            SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            factory.setConnectTimeout(this.connectTimeout);
            factory.setReadTimeout(this.readTimeout);
            return factory;
        }
        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect)
                .setMaxConnPerRoute(this.maxConnectPerRoute).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        factory.setConnectTimeout(this.connectTimeout);
        factory.setReadTimeout(this.readTimeout);
        return factory;
    }

    //初始化RestTemplate,并加入spring的Bean工厂,由spring统一管理
    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(this.createFactory());
        List> converterList = restTemplate.getMessageConverters();

        //重新设置StringHttpMessageConverter字符集为UTF-8,解决中文乱码问题
        HttpMessageConverter converterTarget = null;
        for (HttpMessageConverter item : converterList) {
            if (StringHttpMessageConverter.class == item.getClass()) {
                converterTarget = item;
            }
            break;
        }
        if (null != converterTarget) {
            converterList.remove(converterTarget);
        }
        converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        //加入FastJson转换器
        converterList.add(new FastJsonHttpMessageConverter4());
        return restTemplate;
    }

}

简单工具类

package com.gzkj.admin.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * HTTP 请求工具类
 *
 * @author cjj
 * @date 2019年7月23日
 */

@Slf4j
@Component
public class RestfulUtils {
    @Autowired
    RestTemplate restTemplate;

    public RestfulUtils() {
    }

    public Object getWithHeaders(String url) {
        return requestFor(url, HttpMethod.GET, null, null);
    }

    public Object postWithHeaders(String url, JSONObject body) {
        return requestFor(url, HttpMethod.POST, body, null);
    }

    public Object requestFor(String url, HttpMethod method, JSONObject requestBody) {
        return requestFor(url, method, requestBody, null);
    }

    public Object requestFor(String url, HttpMethod method, JSONObject requestBody, Class tClass) {
        HttpEntity httpEntity = init(method, requestBody);
        System.out.println("url:" + url);
        System.out.println("method:" + method);
        System.out.println("body:" + Optional.ofNullable(requestBody).map(v -> v.toJSONString()).orElse(""));
        ResponseEntity o = restTemplate.exchange(url, method, httpEntity, Object.class);
        HttpHeaders headers = o.getHeaders();
        Object body = o.getBody();
        if (tClass == null) {
            return body;
        }
        if (body instanceof List) {
            List> o1 = (List>) body;
            String s = JSON.toJSONString(o1);
            return JSONArray.parseArray(s, tClass);
        } else if (body instanceof Map) {
            Map o1 = (Map) body;
            String s = JSON.toJSONString(o1);
            return JSON.parseObject(s, tClass);
        }
        return JSON.toJSONString(body);
    }

    private HttpEntity init(HttpMethod method, JSONObject body) {
        HttpHeaders headers = new HttpHeaders();
//        headers.set(HttpHeaders.AUTHORIZATION, restDto.getBasic());
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity> httpEntity = null;
        if (method == HttpMethod.GET) {
            httpEntity = new HttpEntity<>(headers);
        } else if (method == HttpMethod.POST) {
            httpEntity = new HttpEntity(body.toJSONString(), headers);
        }
        return httpEntity;
    }
}
 
  

 

你可能感兴趣的:(springboot (RestTemplate)网络请求封装)