封装httpClient工具类进行get、post、put、delete的http接口请求,可添加请求头与参数,支持多线程

封装httpClient工具类进行get、post、put、delete的http接口请求,可添加请求头与参数,支持多线程首先需要json以及springframework的maven依赖:<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency>

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

首先需要json以及httpclient的maven依赖:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

spring下自动添加token以及支持多线程:

package com.supcon.mare.oms.util.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: zhaoxu
 * @description:
 */
public class HttpClientUtil { 
   
    private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
    private static PoolingHttpClientConnectionManager cm = null;
    private static RequestConfig requestConfig = null;

    static { 
   

        LayeredConnectionSocketFactory sslsf = null;
        try { 
   
            sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
        } catch (NoSuchAlgorithmException e) { 
   
            LOGGER.error("创建SSL连接失败");
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        //多线程调用注意配置,根据线程数设定
        cm.setMaxTotal(200);
        //多线程调用注意配置,根据线程数设定
        cm.setDefaultMaxPerRoute(300);
        requestConfig = RequestConfig.custom()
                //数据传输过程中数据包之间间隔的最大时间
                .setSocketTimeout(20000)
                //连接建立时间,三次握手完成时间
                .setConnectTimeout(20000)
                //重点参数
                .setExpectContinueEnabled(true)
                .setConnectionRequestTimeout(10000)
                //重点参数,在请求之前校验链接是否有效
                .setStaleConnectionCheckEnabled(true)
                .build();
    }

    public static CloseableHttpClient getHttpClient() { 
   
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();
        return httpClient;
    }

    public static void closeResponse(CloseableHttpResponse closeableHttpResponse) throws IOException { 
   
        EntityUtils.consume(closeableHttpResponse.getEntity());
        closeableHttpResponse.close();
    }

    /**
     * get请求,params可为null,headers可为null
     *
     * @param headers
     * @param url
     * @return
     * @throws IOException
     */
    public static String get(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建get请求
        HttpGet httpGet = null;
        List<BasicNameValuePair> paramList = new ArrayList<>();
        if (params != null) { 
   
            Iterator<String> iterator = params.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String paramName = iterator.next();
                paramList.add(new BasicNameValuePair(paramName, params.get(paramName).toString()));
            }
        }
        if (url.contains("?")) { 
   
            httpGet = new HttpGet(url + "&" + EntityUtils.toString(new UrlEncodedFormEntity(paramList, Consts.UTF_8)));
        } else { 
   
            httpGet = new HttpGet(url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(paramList, Consts.UTF_8)));
        }

        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpGet.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpGet.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpGet.setConfig(requestConfig);
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        closeableHttpResponse = httpClient.execute(httpGet);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    /**
     * post请求,params可为null,headers可为null
     *
     * @param headers
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String post(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建post请求
        HttpPost httpPost = new HttpPost(url);
        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpPost.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpPost.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        if (params != null) { 
   
            StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
            httpPost.setEntity(stringEntity);
        }
        closeableHttpResponse = httpClient.execute(httpPost);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    /**
     * delete,params可为null,headers可为null
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String delete(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建delete请求,HttpDeleteWithBody 为内部类,类在下面
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpDelete.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpDelete.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpDelete.setConfig(requestConfig);
        httpDelete.addHeader("Content-Type", "application/json");
        httpDelete.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        if (params != null) { 
   
            StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
            httpDelete.setEntity(stringEntity);
        }
        closeableHttpResponse = httpClient.execute(httpDelete);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    /**
     * put,params可为null,headers可为null
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String put(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建put请求
        HttpPut httpPut = new HttpPut(url);
        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpPut.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpPut.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpPut.setConfig(requestConfig);
        httpPut.addHeader("Content-Type", "application/json");
        httpPut.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        if (params != null) { 
   
            StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
            httpPut.setEntity(stringEntity);
        }
        // 从响应模型中获得具体的实体
        closeableHttpResponse = httpClient.execute(httpPut);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    public static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { 
   
        public static final String METHOD_NAME = "DELETE";

        @Override
        public String getMethod() { 
   
            return METHOD_NAME;
        }

        public HttpDeleteWithBody(final String uri) { 
   
            super();
            setURI(URI.create(uri));
        }

        public HttpDeleteWithBody(final URI uri) { 
   
            super();
            setURI(uri);
        }

        public HttpDeleteWithBody() { 
   
            super();
        }
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/157763.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号