httpclient读取https请求的数据
    compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.3.2'
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime
    compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.3.2'
    compile group: 'com.alibaba', name: 'fastjson', version: '1.2.47'

  

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class SSLUtils {

    private static TrustManager[] trustAllHttpsCertificates() throws KeyManagementException {
        TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

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

    public static CloseableHttpClient createHttpClientSSL() throws NoSuchAlgorithmException, KeyManagementException {
        CloseableHttpClient httpClient = null;
        TrustManager[] trustManagers = trustAllHttpsCertificates();
        SSLContext sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.SSL);
        sslContext.init(null, trustManagers, new SecureRandom());
        httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)).build();

        return httpClient;
    }

    public static CloseableHttpClient createHttpClientTLS() throws NoSuchAlgorithmException, KeyManagementException {
        CloseableHttpClient httpClient = null;
        TrustManager[] trustManagers = trustAllHttpsCertificates();
        SSLContext sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
        sslContext.init(null, trustManagers, new SecureRandom());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpClient;
    }

    public static SSLSocketFactory createSSLSocketFactory() throws Exception {
        TrustManager[] trustManagers = trustAllHttpsCertificates();
        SSLContext sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
        sslContext.init(null, trustManagers, new SecureRandom());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        SSLSocketFactory factory = sslContext.getSocketFactory();
        return factory;
    }

}

  

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


public class RestUtil {

    /**
     * GET请求,获取JSONObject信息
     *
     * @param url
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject get(String url) throws Exception {
        CloseableHttpClient httpclient = SSLUtils.createHttpClientTLS();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                return covertEntityToJSON(response.getEntity());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * GET请求,获取byte数组信息
     *
     * @param url
     * @return byte[]
     * @throws Exception
     */
    public static byte[] getBinary(String url) throws Exception {
        CloseableHttpClient httpclient = SSLUtils.createHttpClientTLS();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                return covertEntityToBinary(response.getEntity());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * POST请求 HTTP
     *
     * @param url
     * @param parameters
     * @return
     * @throws Exception
     */
    public static JSONObject postHttp(String url, JSONObject parameters) throws Exception {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Set<String> keySet = parameters.keySet();
        for (String key : keySet) {
            String value = parameters.get(key).toString();
            if (value.equals("null") != true) {
                nameValuePairs.add(new BasicNameValuePair(key, value));
            }
        }
        return executeSendRequest(httpclient,httpPost,nameValuePairs);
    }

    /**
     * POST请求 HTTPS
     *
     * @param url
     * @param parameters
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject postHttps(String url, JSONObject parameters) throws Exception {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = SSLUtils.createHttpClientTLS();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Set<String> keySet = parameters.keySet();
        for (String key : keySet) {
            String value = parameters.get(key).toString();
            if (value.equals("null") != true) {
                nameValuePairs.add(new BasicNameValuePair(key, value));
            }
        }
        return executeSendRequest(httpClient,httpPost,nameValuePairs);
    }

    /**
     * 执行发送请求
     * @param httpclient
     * @param httpPost
     * @param nameValuePairs
     * @return JSONObject
     * @throws Exception
     */
    private static JSONObject executeSendRequest(CloseableHttpClient httpclient, HttpPost httpPost, List<NameValuePair> nameValuePairs) throws Exception {
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            httpPost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                return covertEntityToJSON(response.getEntity());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将HttpEntity转换成JSONObject
     *
     * @param entity
     * @return JSONObject
     * @throws Exception
     */
    private static JSONObject covertEntityToJSON(HttpEntity entity) throws Exception {
        if (entity != null) {
            String res = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(res);
            return jsonObject;
        } else {
            return null;
        }
    }

    /**
     * 将HttpEntity转换成byte[]
     *
     * @param entity
     * @return byte[]
     * @throws Exception
     */
    private static byte[] covertEntityToBinary(HttpEntity entity) throws Exception {
        if (entity != null) {
            byte[] res = EntityUtils.toByteArray(entity);
            return res;
        } else {
            return null;
        }
    }
}

  

posted on 2020-03-25 12:17  james-roger  阅读(886)  评论(0编辑  收藏  举报