美文网首页
Springboot自带的RestTemplate发送请求与上传

Springboot自带的RestTemplate发送请求与上传

作者: IT小池 | 来源:发表于2023-09-03 15:23 被阅读0次

    首先创建一个RestTemplate对象

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    
        /**
         * 使用客户端类API调用远程交易时必须设置相应的超时时间,如果远程交易有问题如长时间未响应,若未设置超时时间,则会耗尽客户端所在服务器的资源
         */
        // 连接超时
        requestFactory.setConnectTimeout(5000);
        //读超时
        requestFactory.setReadTimeout(10000);
        //连接池获取连接超时时间
        requestFactory.setConnectionRequestTimeout(5000);
    
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //Httpclient连接池的方式,同时支持netty,okHttp以及其他http框架
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        // 最大连接数
        connectionManager.setMaxTotal(200);
        // 同路由并发数
        connectionManager.setDefaultMaxPerRoute(50);
        //配置连接池
        httpClientBuilder.setConnectionManager(connectionManager);
    
        // 最大连接数
        connectionManager.setMaxTotal(500);
        // 同路由并发数(每个主机的并发)
        connectionManager.setDefaultMaxPerRoute(100);
        httpClientBuilder.setConnectionManager(connectionManager);
        requestFactory.setHttpClient(httpClientBuilder.build());
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }
    

    封装请求工具HttpUtil

    package com.demo;
    
    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Component;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.util.ObjectUtils;
    import org.springframework.web.client.RestTemplate;
    
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    
    /** HttpUtil
     * author chics
     * 2023/8/22
     */
    @Slf4j
    @Component
    public class HttpUtil {
    
        public static final String API_KEY_PREFIX = "Api_key";
    
        public static RestTemplate restTemplate;
    
        @Autowired
        public void setRestTemplate(RestTemplate restTemplate) {
            HttpUtil.restTemplate = restTemplate;
        }
    
        /**
         * get请求
         * @param apiKey
         * @param uri
         * @param clazz
         * @return
         */
        public static <T>T get(String apiKey,String uri,Class<T> clazz){
            return get(apiKey,uri,null,null,clazz);
        }
    
        /**
         * get请求
         * @param apiKey
         * @param uri
         * @param body
         * @param clazz
         * @return
         */
        public static <T>T get(String apiKey,String uri,Object body,Class<T> clazz){
            return get(apiKey,uri,body,null,clazz);
        }
    
        /**
         * get请求
         * @param apiKey
         * @param uri
         * @param formParams
         * @param clazz
         * @return
         */
        public static <T>T get(String apiKey,String uri,Map<String,Object> formParams,Class<T> clazz){
            return get(apiKey,uri,null,formParams,clazz);
        }
    
        /**
         * get请求
         * @param apiKey
         * @param uri
         * @param body
         * @param formParams
         * @param clazz
         * @return
         */
        public static <T>T get(String apiKey,String uri,Object body,Map<String,Object> formParams,Class<T> clazz){
            HttpEntity<Object> httpEntity = new HttpEntity<Object>(null, getHttpHeaders(apiKey));
            if (!ObjectUtils.isEmpty(body)){
                httpEntity = new HttpEntity<Object>(body, getHttpHeaders(apiKey));
            }
            if (ObjectUtils.isEmpty(formParams)){
                ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
                return JSON.parseObject(result.getBody(),clazz);
            }
            ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET,httpEntity,String.class,formParams);
            return JSON.parseObject(result.getBody(),clazz);
        }
    
        /**
         * post请求
         * @param apiKey
         * @param uri
         * @param clazz
         * @return
         */
        public static <T>T post(String apiKey,String uri,Class<T> clazz){
            return post(apiKey,uri,null,null,clazz);
        }
    
        /**
         * post请求
         * @param apiKey
         * @param uri
         * @param body
         * @param clazz
         * @return
         */
        public static <T>T post(String apiKey,String uri,Object body,Class<T> clazz){
            return post(apiKey,uri,body,null,clazz);
        }
    
        /**
         * post请求
         * @param apiKey
         * @param uri
         * @param formParams
         * @param clazz
         * @return
         */
        public static <T>T post(String apiKey,String uri,Map<String,Object> formParams,Class<T> clazz){
            return post(apiKey,uri,null,formParams,clazz);
        }
    
        /**
         * post请求
         * @param apiKey
         * @param uri
         * @param body
         * @param formParams
         * @param clazz
         * @return
         */
        public static <T>T post(String apiKey,String uri,Object body,Map<String,Object> formParams,Class<T> clazz){
            HttpEntity<Object> httpEntity = new HttpEntity<Object>(null, getHttpHeaders(apiKey));
            if (!ObjectUtils.isEmpty(body)){
                httpEntity = new HttpEntity<Object>(body, getHttpHeaders(apiKey));
            }
            if (ObjectUtils.isEmpty(formParams)){
                ResponseEntity<String> result = restTemplate.postForEntity(uri, httpEntity, String.class);
                return JSON.parseObject(result.getBody(),clazz);
            }
            ResponseEntity<String> result = restTemplate.postForEntity(uri, httpEntity, String.class,formParams);
            return JSON.parseObject(result.getBody(),clazz);
        }
    
        /**
         * post文件上传请求
         * @param apiKey
         * @param uri
         * @param formParams
         * @param clazz
         * @return
         */
        public static <T>T postUpload(String apiKey, String uri, MultiValueMap<String,Object> formParams,Class<T> clazz){
            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.add(API_KEY_PREFIX,apiKey);
            /*MultiValueMap<String,Object> form = new LinkedMultiValueMap<>();
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                form.add("files", file.getResource());
            }*/
            HttpEntity<Object> httpEntity = new HttpEntity<>(formParams, headers);
            ResponseEntity<String> result = restTemplate.postForEntity(uri, httpEntity, String.class);
            return JSON.parseObject(result.getBody(),clazz);
        }
    
        /**
         * 创建上传文件createForm
         * @return
         */
        public static MultiValueMap<String,Object> createForm(){
            return new LinkedMultiValueMap<>();
        }
    
        /**
         * 获取文件流
         * @param apiKey
         * @param uri
         * @return
         */
        public static byte[] getFileStream(String apiKey,String uri){
            HttpHeaders headers = new HttpHeaders();
            headers.add(API_KEY_PREFIX,apiKey);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));
            HttpEntity<String> entity = new HttpEntity<String>(headers);
            ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class);
            return response.getBody();
        }
    
        /**
         * 获取请求头
         * @param apiKey
         * @return
         */
        private static HttpHeaders getHttpHeaders(String apiKey){
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add(API_KEY_PREFIX,apiKey);
            return headers;
        }
    
        /**
         * 序列化成集合
         * @param data
         * @param clazz
         * @param <T>
         * @return
         */
        public static <T>List<T> toList(Object data,Class<T> clazz){
            return JSON.parseArray(JSON.toJSONString(data)).toJavaList(clazz);
        }
    }
    

    使用就是根据方法参数传值就行。

    相关文章

      网友评论

          本文标题:Springboot自带的RestTemplate发送请求与上传

          本文链接:https://www.haomeiwen.com/subject/jxafvdtx.html