https封装类,支持get/post请求

所需jar:commons-logging-1.1.3.jar、httpclient-4.3.1.jar、httpcore-4.3.jar

package com.onlyou.microfinance.common.util;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
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.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

/**
 * https封装类,支持get、post
 * 
 * @author Administrator
 *
 */
public class HttpsUtil {
    private static CloseableHttpClient client=null;
     
    private static CloseableHttpClient createHttpsClient() {
        if(client!=null){
            return client;
        }
        try {
            X509TrustManager x509mgr = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String string) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String string) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509mgr}, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

             client=HttpClients.custom().setSSLSocketFactory(sslsf).build();
             return client;
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }


    public static HttpEntity doGetByHttps(String url, String host, String cacheControl, String contentType, 
            String acceptCharset, String pragma, String accept, String acceptEncoding, String referer) throws Exception {
        CloseableHttpClient client = createHttpsClient();
        HttpHost httpHost = new HttpHost(host, 443, "https");
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HttpHeaders.CACHE_CONTROL, cacheControl);
        httpGet.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
        httpGet.addHeader(HttpHeaders.ACCEPT_CHARSET, acceptCharset);
        httpGet.addHeader(HttpHeaders.PRAGMA, pragma);
        httpGet.addHeader(HttpHeaders.ACCEPT, accept);
        httpGet.addHeader(HttpHeaders.ACCEPT_ENCODING, acceptEncoding);
        httpGet.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2471.0 Safari/537.36");
        httpGet.addHeader(HttpHeaders.REFERER, referer);
        HttpResponse response = client.execute(httpHost, httpGet);
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            //String result = EntityUtils.toString(httpEntity); 
            //byte[] data = EntityUtils.toByteArray(httpEntity); 
            return entity;
        } else { 
            return null;
        }
    }
    
    public static HttpEntity doGetByHttps(String url, String host, String contentType, String referer) throws Exception {
        return doGetByHttps(url, host, "no-cache", contentType, "utf-8", "no-cache", 
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "gzip, deflate, sdch", referer) ;
    }

    public static HttpEntity doPostByHttps(String url, String host, String cacheControl, String contentType, 
            String acceptCharset, String pragma, String accept, String acceptEncoding, String referer, Map<String, Object> paramMap) {
        HttpHost httpHost = new HttpHost(host, 443, "https");
        HttpPost httpRequst = new HttpPost(url);
        httpRequst.addHeader(HttpHeaders.CACHE_CONTROL, cacheControl);
        httpRequst.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
        httpRequst.addHeader(HttpHeaders.ACCEPT_CHARSET, acceptCharset);
        httpRequst.addHeader(HttpHeaders.PRAGMA, pragma);
        httpRequst.addHeader(HttpHeaders.ACCEPT, accept);
        httpRequst.addHeader(HttpHeaders.ACCEPT_ENCODING, acceptEncoding);
        httpRequst.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2471.0 Safari/537.36");
        httpRequst.addHeader(HttpHeaders.REFERER, referer);

        List<NameValuePair> params = new ArrayList<>();
        if (paramMap != null && !paramMap.isEmpty()) {
            for (String key : paramMap.keySet()) {
                params.add(new BasicNameValuePair(key, (String) paramMap.get(key)));
            }
        }

        try {
            httpRequst.setEntity(new UrlEncodedFormEntity(params));
            CloseableHttpClient client = createHttpsClient();
            HttpResponse httpResponse = client.execute(httpHost, httpRequst);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                //String result = EntityUtils.toString(httpEntity); 
                //byte[] data = EntityUtils.toByteArray(httpEntity); 
                return httpEntity;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  
        return null;
    }
    
    public static HttpEntity doPostByHttps(String url, String host, String contentType, String referer, Map<String, Object> paramMap) throws Exception {
        return doPostByHttps(url, host, "no-cache", contentType, "utf-8", "no-cache", 
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "gzip, deflate, sdch", referer, paramMap) ;
    }
}

调用示例:

HttpEntity loginEntity = HttpsUtil.doPostByHttps(url, "ipcrs.pbccrc.org.cn", "application/x-www-form-urlencoded", "https://*/page/login/loginreg.jsp", map);

HttpEntity entity = HttpsUtil.doGetByHttps(url, host, "image/jpeg", "https://*/page/login/loginreg.jsp");
原文地址:https://www.cnblogs.com/linjiqin/p/4745934.html