HTTP请求客户端工具类

Stella981
• 阅读 725

1.maven 引入依赖

<dependency>    <groupId>commons-httpclient</groupId>    <artifactId>commons-httpclient</artifactId>    <version>3.1</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --><dependency>    <groupId>org.apache.commons</groupId>    <artifactId>commons-lang3</artifactId>    <version>3.4</version></dependency>

2.HTTP请求客户端工具类代码

package com.vx.springbootexcel.common.utils;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.RequestEntity;import org.apache.commons.httpclient.methods.StringRequestEntity;import org.apache.commons.httpclient.params.HttpConnectionManagerParams;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.commons.lang3.StringUtils;import org.hibernate.validator.internal.util.StringHelper;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.zip.GZIPInputStream;/** * HTTP请求客户端工具类 * * @author yaojz * @version 1.0 */public class HttpClientUtil {   // protected static InnerLogger logger = new GpLoggerWrapper().new InnerLogger(HttpClientUtil.class);    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);    private static HttpClient httpClient;    private static int HTTP_TIMEOUT = 60000;    private HttpClientUtil() {    }    private final static HttpClient getInstance() {        if (httpClient == null) {            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();            HttpConnectionManagerParams params = new HttpConnectionManagerParams();            params.setConnectionTimeout(HTTP_TIMEOUT);            params.setSoTimeout(HTTP_TIMEOUT);            params.setMaxTotalConnections(10000);            params.setDefaultMaxConnectionsPerHost(1000);            connectionManager.setParams(params);            httpClient = new HttpClient(connectionManager);            httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));        }        return httpClient;    }    /**     * 通过HTTP协议请求     *     * @param url        不能为空     * @param parameters 可为空     * @return 目标地址响应内容     * @throws Exception 网络异常     */    public static String getRequest_ResponseBodyAsString(String url, Map<String, String> parameters) throws Exception {        if (url == null) {            logger.warn(" the url is null");            return "";        }        String params = parameterToString(parameters, "utf-8");        logger.debug("HttpGet请求:" + url + (params != null ? url.contains("?") ? "&" + params : "?" + params : ""));        GetMethod method = new GetMethod(url + (params != null ? url.contains("?") ? "&" + params : "?" + params : ""));        int statusCode;        try {            // method.addRequestHeader("Accept-Encoding", "gzip, deflate");            statusCode = HttpClientUtil.getInstance().executeMethod(method);            if (statusCode != HttpStatus.SC_OK) {                logger.error("Method failed: " + method.getStatusLine());                throw new Exception("请求的服务器有异常:服务器状态码为" + statusCode);            }            if (method.getResponseHeader("Content-Encoding") != null) {                String acceptEncoding = method.getResponseHeader("Content-Encoding").getValue();                if (acceptEncoding.toLowerCase().indexOf("gzip") > -1) {                    // 建立gzip解压工作流                    StringBuffer sb = new StringBuffer();                    InputStream is = method.getResponseBodyAsStream();                    GZIPInputStream gzin = new GZIPInputStream(is);                    InputStreamReader isr = new InputStreamReader(gzin); // 设置读取流的编码格式                    // ,                    // 自定义编码                    BufferedReader br = new BufferedReader(isr);                    String tempbf;                    while ((tempbf = br.readLine()) != null) {                        sb.append(tempbf);                        sb.append("\r\n");                    }                    isr.close();                    gzin.close();                    return sb.toString();                }            }            return method.getResponseBodyAsString();        } catch (Throwable e) {            throw new Exception("Http服务链路异常:" + e.getMessage(), e);        } finally {            method.releaseConnection();        }    }    public static String streamRequest_ResponseBodyAsString(String url, String param) throws Exception {        if (StringHelper.isNullOrEmptyString(url)) {            logger.warn(" the url is null");            return "";        }        logger.debug("Http写流请求:" + url + (param != null ? url.contains("?") ? "&" + param : "?" + param : ""));        OutputStream out = null;        BufferedReader in = null;        String result = "";        try {            URL realUrl = new URL(url);            // 打开和URL之间的连接            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();            // 设置通用的请求属性            conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length));            conn.setRequestProperty("Content-Type", "text/xml;charset=utf8");            conn.setRequestProperty("connection", "Keep-Alive");            conn.setRequestMethod("POST");            // 发送POST请求必须设置如下两行            conn.setDoOutput(true);            conn.setReadTimeout(60000);            conn.setConnectTimeout(60000);            conn.setDoInput(true);            // 获取URLConnection对象对应的输出流            out = conn.getOutputStream();            // 发送请求参数            out.write(param.getBytes("UTF-8"));            // flush输出流的缓冲            out.flush();            // 定义BufferedReader输入流来读取URL的响应            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));            String line;            while ((line = in.readLine()) != null) {                result += "\n" + line;            }            conn.disconnect();        } catch (Throwable e) {            throw new Exception("Http服务链路异常:" + e.getMessage(), e);        } finally {            try {                if (out != null) {                    out.close();                }                if (in != null) {                    in.close();                }            } catch (IOException e) {                logger.error(e.getMessage(), e);            }        }        return result;    }    public static String postRequest_ResponseBodyAsString(String url, Map<String, String> parameters) throws Exception {        if (StringHelper.isNullOrEmptyString(url)) {            logger.warn(" the url is null");            return "";        }        logger.debug("HttpPost请求:" + url + (parameters != null ? url.contains("?") ? "&" + parameters : "?" + parameters : ""));        PostMethod method = new PostMethod(url);        int statusCode;        try {            for (String key : parameters.keySet()) {                method.addParameter(key, parameters.get(key));            }            method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");            statusCode = HttpClientUtil.getInstance().executeMethod(method);            if (statusCode != HttpStatus.SC_OK) {                logger.error("Method failed: " + method.getStatusLine());                throw new Exception("Http服务链路异常:服务器状态码为" + statusCode);            }            return method.getResponseBodyAsString();        } catch (Throwable e) {            throw new Exception("Http服务链路异常:" + e.getMessage(), e);        } finally {            method.releaseConnection();        }    }    /**     * 以POST方式发送请求     *     * @param url     * @param parameters     * @return 返回字节内容     * @throws Exception     */    public static byte[] postRequest_ResponseBodyAsBytes(String url, Map<String, String> parameters) throws Exception {        logger.debug("HttpPost请求:" + url + (parameters != null ? url.contains("?") ? "&" + parameters : "?" + parameters : ""));        PostMethod method = new PostMethod(url);        int statusCode;        try {            for (String key : parameters.keySet()) {                method.addParameter(key, parameters.get(key));            }            method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");            // method.setRequestHeader("Accept-Encoding", "gzip, deflate");            statusCode = httpClient.executeMethod(method);            if (statusCode != HttpStatus.SC_OK) {                logger.error("Method failed: " + method.getStatusLine());                throw new Exception("Http服务链路异常:服务器状态码为" + statusCode);            }            return method.getResponseBody();        } catch (Throwable e) {            throw new Exception("Http服务链路异常:" + e.getMessage(), e);        } finally {            // Release the connection.            method.releaseConnection();        }    }    /**     * 以POST方式发送请求     *     * @param url     * @param parameters     * @return 返回流     * @throws Exception     */    public static InputStream postRequest_ResponseBodyAsStream(String url, Map<String, String> parameters) throws Exception {        logger.debug("HttpPost请求:" + url + (parameters != null ? url.contains("?") ? "&" + parameters : "?" + parameters : ""));        PostMethod method = new PostMethod(url);        int statusCode;        try {            for (String key : parameters.keySet()) {                method.addParameter(key, parameters.get(key));            }            method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");            // method.setRequestHeader("Accept-Encoding", "gzip, deflate");            statusCode = httpClient.executeMethod(method);            if (statusCode != HttpStatus.SC_OK) {                logger.error("Method failed: " + method.getStatusLine());                throw new Exception("Http服务链路异常:服务器状态码为" + statusCode);            }            return method.getResponseBodyAsStream();        } catch (Throwable e) {            throw new Exception("Http服务链路异常:" + e.getMessage(), e);        } finally {            // Release the connection.            method.releaseConnection();        }    }    // 对参数编码组合成一个get请求参数串    private static String parameterToString(Map<String, String> parameters, String input_charset) {        if (parameters != null) {            StringBuffer result = new StringBuffer();            List<String> keys = new ArrayList<String>(parameters.keySet());            for (int i = 0; i < keys.size(); i++) {                try {                    String key = (String) keys.get(i);                    String value = (String) parameters.get(key);                    if (i == keys.size() - 1) {                        result.append(key).append("=").append(URLEncoder.encode(value, input_charset));                    } else {                        result.append(key).append("=").append(URLEncoder.encode(value, input_charset)).append("&");                    }                } catch (UnsupportedEncodingException e) {                    logger.error(e.getMessage(), e);                }            }            return result.toString();        }        return null;    }    /**     * 通过HTTP协议请求     *     * @param url      不能为空     * @param postBody 不能为空     * @param tokenId     * @return 目标地址响应内容     * @throws Exception 网络异常     */    public static String postJSONRequest(String url, String postBody,String tokenId) throws Exception {        if (StringHelper.isNullOrEmptyString(url)) {            logger.warn(" the url is null");            return "";        }        logger.debug("HttpPost请求:" + url + postBody);        PostMethod method = new PostMethod();        try {            method.setURI(new URI(url, true, "UTF-8"));        } catch (URIException e1) {            throw new Exception("解析URL出错:" + url);        } catch (NullPointerException e1) {            throw new Exception("解析URL出错:" + url);        }        method.setRequestHeader("Content-type", "application/json; charset=UTF-8");        if(StringUtils.isNotBlank(tokenId)){            method.setRequestHeader("tokenId", tokenId);        }        RequestEntity requestEntity = new StringRequestEntity(postBody);        method.setRequestEntity(requestEntity);        int statusCode;        try {            statusCode = HttpClientUtil.getInstance().executeMethod(method);            if (statusCode != HttpStatus.SC_OK) {                logger.error("Method failed: " + method.getStatusLine());                throw new Exception("请求的服务器有异常:服务器状态码为" + statusCode);            }            BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), method.getResponseCharSet()));            StringBuffer sb = new StringBuffer();            int chari2;            while ((chari2 = in.read()) != -1) {                sb.append((char) chari2);            }            return sb.toString();        } catch (Throwable e) {            throw new Exception("Http服务链路异常:" + e.getMessage(), e);        } finally {            if (method != null) {                method.releaseConnection();            }        }    }    public static String streamRequest_ResponseBodyAsStringWithUTF8(String url, String param) throws Exception {        if (StringHelper.isNullOrEmptyString(url)) {            logger.warn(" the url is null");            return "";        }        logger.debug("Http写流请求:" + url + (param != null ? url.contains("?") ? "&" + param : "?" + param : ""));        OutputStream out = null;        BufferedReader in = null;        String result = "";        try {            URL realUrl = new URL(url);            // 打开和URL之间的连接            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();            // 设置通用的请求属性            conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length));            conn.setRequestProperty("Content-Type", "text/xml;charset=utf8");            conn.setRequestProperty("connection", "Keep-Alive");            conn.setRequestMethod("POST");            // 发送POST请求必须设置如下两行            conn.setDoOutput(true);            conn.setReadTimeout(60000);            conn.setConnectTimeout(60000);            conn.setDoInput(true);            // 获取URLConnection对象对应的输出流            out = conn.getOutputStream();            // 发送请求参数            out.write(param.getBytes("UTF-8"));            // flush输出流的缓冲            out.flush();            // 定义BufferedReader输入流来读取URL的响应            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));            String line;            while ((line = in.readLine()) != null) {                result += "\n" + line;            }            conn.disconnect();        } catch (Throwable e) {            throw new Exception("Http服务链路异常:" + e.getMessage(), e);        } finally {            try {                if (out != null) {                    out.close();                }                if (in != null) {                    in.close();                }            } catch (IOException e) {                logger.error(e.getMessage(), e);            }        }        return result.trim();    }}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这