All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.doudou.common.tool.rpc.FastRestTemplate Maven / Gradle / Ivy

There is a newer version: 1.3.2
Show newest version
package top.doudou.common.tool.rpc;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import top.doudou.base.exception.ConnectionException;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;

import static top.doudou.common.tool.utils.UrlUtil.createUrl;


/**
 * @author  傻男人<[email protected]>
 * @Date: 2020/4/20
 * @Description:  RestTemplate的工具类
 */
public class FastRestTemplate {
    
    private static RestTemplate restTemplate = getInstance();

    public static RestTemplate getInstance() {
        if (restTemplate == null) {
            synchronized (FastRestTemplate.class) {
                if (restTemplate == null) {
                    restTemplate = new RestTemplate();
                    restTemplate.setRequestFactory(crateClientHttpRequestFactory());
                    restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
                }
            }
        }
        return restTemplate;
    }

    private static ClientHttpRequestFactory crateClientHttpRequestFactory() {
        FastRestTemplateRequestFactory httpComponentsClientHttpRequestFactory = new FastRestTemplateRequestFactory();
        httpComponentsClientHttpRequestFactory.setConnectTimeout(10000);
        httpComponentsClientHttpRequestFactory.setReadTimeout(10000);
        return httpComponentsClientHttpRequestFactory;
    }

    // --------------------------------post-------------------------------------------------------------

    /**
     * 表单的提交方式
     * @param url 请求的地址
     * @param parameters 请求的参数
     * @param responseType 返回的类型
     * @return
     */
    public T fromPost(String url, Map parameters,Class responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return fromPost(url, parameters, headers,responseType);
    }

    public T fromPost(String url, Map parameters, HttpHeaders headers,Class responseType) {
        MultiValueMap map = new LinkedMultiValueMap<>();
        parameters.forEach((key,value)->map.add(key,value));
        HttpEntity request = new HttpEntity<>(map, headers);
        try {
            ResponseEntity response = restTemplate.postForEntity(url, request, responseType);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    /**
     * 文件流的post请求方式
     * @param url 请求的url
     * @param headers header
     * @param params 参数
     * @param fileSystemResource  文件流
     * @param responseType 返回的类型
     * @return
     */
    public T postUploadFile(String url, HttpHeaders headers, Map params, FileSystemResource fileSystemResource,Class responseType) {
        HttpEntity httpEntity = new HttpEntity<>(fileSystemResource, headers);
        try {
            ResponseEntity response = restTemplate.postForEntity(url, httpEntity, responseType, params);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    /**
     * 常用的请求的方式
     * @param url  请求的url
     * @param t 参数
     * @param target 返回的类型
     * @return
     */
    public  E postForEntity(String url, T t, Class target) {
        HttpHeaders headers = new HttpHeaders();
        //设置类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        return postForEntity(url, t, target, headers);
    }

    /**
     * 常用的post 带请求头
     * @param url  请求的url
     * @param t 参数
     * @param target 返回的类型
     * @param headers 请求头
     * @return
     */
    public  E postForEntity(String url, T t, Class target, HttpHeaders headers) {
        HttpEntity formEntity = new HttpEntity<>(JSONObject.toJSON(t), headers);
        try {
            //发送数据方法
            ResponseEntity forEntity = restTemplate.postForEntity(url, formEntity, target);
            return forEntity.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    //--------------- get -----------------------------

    /**
     * get-无参的方式
     * @param url 请求的地址
     * @param target  返回类
     * @param 
     * @return
     */
    public  T get(String url, Class target) {
        try {
            return restTemplate.getForEntity(url, target).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    /**
     * get-无参的方式(带请求头的方式)
     * @param url 请求的地址
     * @param target  返回类
     * @param 
     * @return
     */
    public  T get(String url, Map headers,Class target) {
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setAll(headers);
            HttpEntity requestEntity = new HttpEntity(null, httpHeaders);
            ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.GET, requestEntity, target);
            return exchange.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    /**
     * get-带参的方式
     * @param url 请求的地址 url中包含占位符{} 如 http://localhost:8080/{id}/?age={age}
     * @param parameters 需要与url中的占位符对应
     * @param target  返回类
     * @return
     */
    public  T getForEntity(String url, Map parameters, Class target) {
        return get(createUrl(url,parameters),target);
    }

    /**
     * get-带参的方式(带header的方式)
     * @param url 请求的地址 url中包含占位符{} 如 http://localhost:8080/{id}/?age={age}
     * @param parameters 需要与url中的占位符对应
     * @param target  返回类
     * @return
     */
    public  T getForEntity(String url, Map headers,Map parameters, Class target) {
        return get(createUrl(url,parameters),headers,target);
    }

    /**
     * get-实体类参数的方式(参数非bady得方式)
     * @param url 请求的地址
     * @param entity 实体类
     * @param target  返回类
     * @return
     */
    public  T getForEntity(String url, E entity, Class target) {
        return get(createUrl(url,entity),target);
    }

    /**
     * get-实体类参数的方式(参数非bady得方式)(带header得方式)
     * @param url 请求的地址
     * @param entity 实体类
     * @param target  返回类
     * @return
     */
    public  T getForEntity(String url,Map headers, E entity, Class target) {
        return get(createUrl(url,entity),headers,target);
    }

    /**
     * get-Body实体类参数的方式
     * @param url 请求的地址
     * @param entity 实体类
     * @param target  返回类
     * @return
     */
    public  T getForBody(String url, E entity, Class target) {
        try {
            HttpHeaders httpHeaders = defaultHttpHeaders();
            httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            HttpEntity requestEntity = new HttpEntity(entity, httpHeaders);
            ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.GET, requestEntity, target);
            return exchange.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    /**
     * get-Body实体类参数的方式(带header得方式)
     * @param url 请求的地址
     * @param entity 实体类
     * @param target  返回类
     * @return
     */
    public  T getForBody(String url, Map headers,E entity, Class target) {
        try {
            HttpEntity httpEntity = getHttpEntity(headers,entity);
            ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, target);
            return exchange.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    /**
     * delete请求封装
     * @param url 请求的参数(url如果传参需要用占位符表示)
     * @param parameters 参数
     * @param headers 请求头
     * @return
     */
    public  T delete(String url,Map headers,Map parameters,Class target) {
        try {
            HttpEntity httpEntity = getHttpEntity(headers);
            ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, target, parameters);
            return exchange.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    /**
     * put请求封装
     * @param url 请求的参数(url如果传参需要用占位符表示)
     * @param t 参数
     * @param headers 请求头
     * @return
     */
    public  E put(String url,HttpHeaders headers, T t,Class target) {
        try {
            HttpHeaders httpHeaders = defaultHttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity httpEntity = new HttpEntity(t,httpHeaders);
            restTemplate.put(url, httpEntity, target);
            ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, target);
            return exchange.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConnectionException("无响应或者响应结果异常");
        }
    }

    public  T header(String url, HttpMethod httpMethod, Map headerMap, Class target) {
        return restTemplate.exchange(url, httpMethod, getHttpEntity(headerMap), target).getBody();
    }

    private static HttpEntity getHttpEntity(Map headers) {
        HttpHeaders httpHeaders = defaultHttpHeaders();
        httpHeaders.setAll(headers);
        return new HttpEntity(null, httpHeaders);
    }

    private static  HttpEntity getHttpEntity(Map headers,E entity) {
        HttpHeaders httpHeaders = defaultHttpHeaders();
        httpHeaders.setAll(headers);
        return new HttpEntity(entity, httpHeaders);
    }

    /**
     * 创建默认的HttpHeaders
     * @return
     */
    private static HttpHeaders defaultHttpHeaders(){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return httpHeaders;
    }

}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy