HTTP請求客戶端工具類

1.maven 引入依賴java

<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請求客戶端工具類代碼spring

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();    }}
相關文章
相關標籤/搜索