[工具類-HttpClientUtils]HttpClient之GET PUT DELETE POST

圖片來自網(wǎng)絡(luò)

發(fā)送http請求: get put delete post


package com.zefun.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * @Description <HTTpClient>
 * @author liwang
 * @date 2017年11月14日
 * @version
 */
public class HttpClientUtil {

    /**
     * HTTP協(xié)議
     */
    private static final String HTTPS_PROTOCOL = "https://";
    /**
     * 協(xié)議默認(rèn)端口
     */
    private static final int HTTPS_PROTOCOL_DEFAULT_PORT = 443;

    /**
     * 默認(rèn)編碼格式
     */
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 日志
     */
    private static Logger logger = Logger.getLogger(HttpClientUtil.class);

    /**
     * 
    * @author 
    * @date 
    * @param url 路徑
    * @return int
     */
    private static int getPort(String url) {
        int startIndex = url.indexOf("://") + "://".length();
        String host = url.substring(startIndex);
        if (host.indexOf("/") != -1) {
            host = host.substring(0, host.indexOf("/"));
        }
        int port = HTTPS_PROTOCOL_DEFAULT_PORT;
        if (host.contains(":")) {
            int i = host.indexOf(":");
            port = new Integer(host.substring(i + 1));
        }
        return port;
    }

    /**
     * 
    * @author 
    * @date 
    * @param params 參數(shù)
    * @return List<NameValuePair>
     */
    private static List<NameValuePair> geneNameValPairs(Map<String, ?> params) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        if (params == null) {
            return pairs;
        }
        for (String name : params.keySet()) {
            if (params.get(name) == null) {
                continue;
            }
            pairs.add(new BasicNameValuePair(name, params.get(name).toString()));
        }
        return pairs;
    }

    /**
     * 發(fā)送GET請求
     * @param url 請求地址
     * @param charset 返回?cái)?shù)據(jù)編碼
     * @return 返回?cái)?shù)據(jù)
     */
    public static String sendGetReq(final String url, String charset) {
        if (null == charset){
            charset = DEFAULT_CHARSET;
        }
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {
            initSSL(httpClient, getPort(url));
        }
        try {
            // 提交請求并以指定編碼獲取返回?cái)?shù)據(jù)
            HttpResponse httpResponse = httpClient.execute(get);
            int statuscode = httpResponse.getStatusLine().getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                Header header = httpResponse.getFirstHeader("location");
                if (header != null) {
                    String newuri = header.getValue();
                    if ((newuri == null) || (newuri.equals(""))){
                        newuri = "/";
                    }
                    try {
                        httpClient.close();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        httpClient = null;
                    }
                    logger.info("重定向地址:" + newuri);
                    return sendGetReq(newuri, null);
                }
            }
            logger.info("請求地址:" + url + ";響應(yīng)狀態(tài):" + httpResponse.getStatusLine());
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, charset);
        }
        catch (ClientProtocolException e) {
            logger.error("協(xié)議異常,堆棧信息如下", e);
        }
        catch (IOException e) {
            logger.error("網(wǎng)絡(luò)異常,堆棧信息如下", e);
        }
        finally {
            // 關(guān)閉連接,釋放資源
            try {
                httpClient.close();
            }
            catch (Exception e) {
                e.printStackTrace();
                httpClient = null;
            }
        }
        return null;
    }

    /**
     * 發(fā)送put請求
     * @param url       請求地址
     * @param params    請求參數(shù)
     * @param charset   返回?cái)?shù)據(jù)編碼
     * @return String
     */
    public static String sendPutReq(String url, Map<String, Object> params, String charset) {
        if (null == charset){
            charset = DEFAULT_CHARSET;
        }
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPut put = new HttpPut(url);

        // 封裝請求參數(shù)
        List<NameValuePair> pairs = geneNameValPairs(params);
        try {
            put.setEntity(new UrlEncodedFormEntity(pairs, charset));
            if (url.startsWith(HTTPS_PROTOCOL)) {
                initSSL(httpClient, getPort(url));
            }
            // 提交請求并以指定編碼獲取返回?cái)?shù)據(jù)
            HttpResponse httpResponse = httpClient.execute(put);

            logger.info("請求地址:" + url + ";響應(yīng)狀態(tài):" + httpResponse.getStatusLine());
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, charset);
        }
        catch (ClientProtocolException e) {
            logger.error("協(xié)議異常,堆棧信息如下", e);
        }
        catch (IOException e) {
            logger.error("網(wǎng)絡(luò)異常,堆棧信息如下", e);
        }
        finally {
            // 關(guān)閉連接,釋放資源
            try {
                httpClient.close();
            }
            catch (Exception e) {
                e.printStackTrace();
                httpClient = null;
            }
        }
        return null;
    }

    /**
     * 發(fā)送delete請求
     * @param url       請求地址
     * @param charset   返回?cái)?shù)據(jù)編碼
     * @return String
     */
    public static String sendDelReq(String url, String charset) {
        if (null == charset){
            charset = DEFAULT_CHARSET;
        }
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpDelete del = new HttpDelete(url);
        if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {
            initSSL(httpClient, getPort(url));
        }
        try {
            // 提交請求并以指定編碼獲取返回?cái)?shù)據(jù)
            HttpResponse httpResponse = httpClient.execute(del);
            logger.info("請求地址:" + url + ";響應(yīng)狀態(tài):" + httpResponse.getStatusLine());
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, charset);
        }
        catch (ClientProtocolException e) {
            logger.error("協(xié)議異常,堆棧信息如下", e);
        }
        catch (IOException e) {
            logger.error("網(wǎng)絡(luò)異常,堆棧信息如下", e);
        }
        finally {
            // 關(guān)閉連接,釋放資源
            try {
                httpClient.close();
            }
            catch (Exception e) {
                e.printStackTrace();
                httpClient = null;
            }
        }
        return null;
    }

    /**
     * 發(fā)送POST請求,支持HTTP與HTTPS
     * @param url 請求地址
     * @param params 請求參數(shù)
     * @param charset 返回?cái)?shù)據(jù)編碼
     * @return 返回?cái)?shù)據(jù)
     */
    public static String sendPostReq(String url, Map<String, ?> params, String charset) {
        if (null == charset){
            charset = DEFAULT_CHARSET;
        }
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        RequestConfig reqConf = RequestConfig.DEFAULT;
        HttpPost httpPost = new HttpPost(url);
        // 封裝請求參數(shù)
        List<NameValuePair> pairs = geneNameValPairs(params);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
            // 對HTTPS請求進(jìn)行處理
            if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {
                initSSL(httpClient, getPort(url));
            }
            // 提交請求并以指定編碼獲取返回?cái)?shù)據(jù)
            httpPost.setConfig(reqConf);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statuscode = httpResponse.getStatusLine().getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                Header header = httpResponse.getFirstHeader("location");
                if (header != null) {
                    String newuri = header.getValue();
                    if ((newuri == null) || (newuri.equals(""))){
                        newuri = "/";
                    }
                    try {
                        httpClient.close();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        httpClient = null;
                    }
                    return sendGetReq(newuri, null);
                }
            }

            logger.info("請求地址:" + url + ";響應(yīng)狀態(tài):" + httpResponse.getStatusLine());
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, charset);
        }
        catch (UnsupportedEncodingException e) {
            logger.error("不支持當(dāng)前參數(shù)編碼格式[" + charset + "],堆棧信息如下", e);
        }
        catch (ClientProtocolException e) {
            logger.error("協(xié)議異常,堆棧信息如下", e);
        }
        catch (IOException e) {
            logger.error("網(wǎng)絡(luò)異常,堆棧信息如下", e);
        }
        finally {
            // 關(guān)閉連接,釋放資源
            try {
                httpClient.close();
            }
            catch (Exception e) {
                e.printStackTrace();
                httpClient = null;
            }
        }
        return null;
    }

    /**
     * 發(fā)送POST請求,支持HTTP與HTTPS, 參數(shù)放入請求體方式
     * @param url 請求地址
     * @param content 請求參數(shù)
     * @param charset 返回?cái)?shù)據(jù)編碼
     * @return 返回?cái)?shù)據(jù)
     */
    public static String sendPost(String url, String content, String charset) {
        if (null == charset){
            charset = DEFAULT_CHARSET;
        }
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        RequestConfig reqConf = RequestConfig.DEFAULT;
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new StringEntity(content, charset));
            // 對HTTPS請求進(jìn)行處理
            if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {
                initSSL(httpClient, getPort(url));
            }
            // 提交請求并以指定編碼獲取返回?cái)?shù)據(jù)
            httpPost.setConfig(reqConf);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statuscode = httpResponse.getStatusLine().getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                Header header = httpResponse.getFirstHeader("location");
                if (header != null) {
                    String newuri = header.getValue();
                    if ((newuri == null) || (newuri.equals(""))){
                        newuri = "/";
                    }
                    try {
                        httpClient.close();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        httpClient = null;
                    }
                    return sendGetReq(newuri, null);
                }
            }

            logger.info("請求地址:" + url + ";響應(yīng)狀態(tài):" + httpResponse.getStatusLine());
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, charset);
        }
        catch (UnsupportedEncodingException e) {
            logger.error("不支持當(dāng)前參數(shù)編碼格式[" + charset + "],堆棧信息如下", e);
        }
        catch (ClientProtocolException e) {
            logger.error("協(xié)議異常,堆棧信息如下", e);
        }
        catch (IOException e) {
            logger.error("網(wǎng)絡(luò)異常,堆棧信息如下", e);
        }
        finally {
            // 關(guān)閉連接,釋放資源
            try {
                httpClient.close();
            }
            catch (Exception e) {
                e.printStackTrace();
                httpClient = null;
            }
        }
        return null;
    }

    /**
     * 初始化HTTPS請求服務(wù)
     * @param httpClient HTTP客戶端
     * @param port 端口
     */
    public static void initSSL(CloseableHttpClient httpClient, int port) {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            final X509TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            // 使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用
            sslContext.init(null, new TrustManager[] { trustManager }, null);
            ConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext);
            Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create().register("https", ssf).build();
            BasicHttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(r);
            HttpClients.custom().setConnectionManager(ccm).build();
        }
        catch (KeyManagementException e) {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容