封装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();
        }
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 使用joi来验证数据模型[通俗易懂]

    使用joi来验证数据模型[通俗易懂]我们用nodejs实现一些功能时,往往需要对用户输入的数据进行验证。然而,验证是一件麻烦的事情,很有可能你需要验证数据类型,长度,特定规则等等,在前端做表单验证时,我们常用的做法是使用正则,正则表达式

    2022年8月1日
    17
  • openwrt旁路由 ipv6上网配置[通俗易懂]

    openwrt旁路由 ipv6上网配置[通俗易懂]openwrt旁路由ipv6上网配置路由器:小米AX3600旁路由:openwrt配置路由端配置上网方式选择:路由器拨号选Native,光猫拨号选NAT6,校园网一般选NAT6打开成功后,上网信息会显示ipv6信息软路由配置DHCP/DNS配置:网络-接口配置:测试IPv6测试…

    2022年5月8日
    425
  • host process for windows services已停止工作_diagnostic service host启动不了

    host process for windows services已停止工作_diagnostic service host启动不了解决WINXP系统开机后弹出Generichostprocessforwin32services遇到问题需要关闭!出现上面这个错误一般有三种情况。1.就是病毒。开机后会提示GenericHostProcessforWin32Services遇到问题需要关闭”“RemoteRrocedureCall(RPC)服务意外终止,然后就自…

    2022年10月12日
    4
  • Java实现扫雷小游戏【优化版】

    Java实现扫雷小游戏【优化版】游戏的设计类似windows扫雷,用户在图形化用户界面内利用鼠标监听事件标记雷区,左上角表示剩余雷的数量,右上角动态显示使用的时间。用户可选择中间组件按钮重新游戏。在使用Java编写扫雷小游戏时遇到了很多问题,在解决问题时,确实对java的面向对象编程有了更加深入的理解。虽然GUI现在并没有很大的市场,甚至好多初学者已经放弃了学习GUI,但是利用GUI编程的过程对于培养编程兴趣,深入理解Java编程有很大的作用。

    2022年7月15日
    16
  • Spring Boot整合RabbitMQ详细教程

    Spring Boot整合RabbitMQ详细教程1.首先我们简单了解一下消息中间件的应用场景异步处理场景说明:用户注册后,需要发注册邮件和注册短信,传统的做法有两种1.串行的方式;2.并行的方式(1)串行方式:将注册信息写入数据库后,发送注册邮件,再发送注册短信,以上三个任务全部完成后才返回给客户端。这有一个问题是,邮件,短信并不是必须的,它只是一个通知,而这种做法让客户端等待没有必要等待的东西.(2)并行方式:将注册信…

    2022年5月14日
    37
  • icem网格数和节点数_icem如何查看网格数量[通俗易懂]

    icem网格数和节点数_icem如何查看网格数量[通俗易懂]>减少总块数,加速求解关键:统一索引y/j索引空间索引空间x/i结构网格的索引与合并ICEM中块的合并Autodyn中网格的合并结构网格的索引与合并索引……网格的索引合并->减少总块数,加速求解关键:统一索引y/j索引空间索引空间x/i结构网格的索引与合并ICEM中块的合并Autodyn中网格的合并结构网格的……选择…

    2022年5月25日
    112

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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