Java教程

Java使用实现无验证书的HTTPS请求

本文主要是介绍Java使用实现无验证书的HTTPS请求,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文章目录

package tv.huan.common.utils.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;


public class HttpsUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpsUtils.class);


    /**
     * 融合平台post调用示例
     */
    public static String rhptGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        SSLClient httpClient = null;
        httpGet.addHeader("User-Agent", "Mozilla/5.0(Windows NT 6.1;Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        httpGet.addHeader("Content-type", "application/x-www-form-urlencoded");
        httpGet.addHeader("other", "xxxxx");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("paramA", "xxxxxxx");
        jsonObject.put("paramB", "123");
        List<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("jsonData", jsonObject.toString()));
        String respMsg = "";
        try {
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, HTTP.UTF_8);
            httpClient = new HttpsUtils().new SSLClient(); // 与DefaultHttpClient httpClient = new DefaultHttpClient(); enableSSL(httpClient); 等价
            // DefaultHttpClient httpClient = new DefaultHttpClient();
            // enableSSL(httpClient);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            respMsg = EntityUtils.toString(httpEntity, "utf-8");

            log.info("发送HTTPS的get请求获取到的响应为" + respMsg);
        } catch (Exception e) {
            log.error("发送HTTPS的get请求异常", e);
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
//        post.setEntity(urlEncodedFormEntity);

        return respMsg;
    }

    /**
     * 融合平台post调用示例
     */
    public static String rhptPost(String url, String params) {
        HttpPost post = new HttpPost(url);
        SSLClient httpClient = null;
        post.addHeader("User-Agent", "Mozilla/5.0(Windows NT 6.1;Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        post.addHeader("Content-type", "application/x-www-form-urlencoded");
        post.addHeader("other", "xxxxx");

//        JSONObject jsonObject = new JSONObject();
//
//        List<NameValuePair> list = new ArrayList<>();
//        list.add(new BasicNameValuePair("jsonData", jsonObject.toString()));
        String respMsg = "";
        try {
            post.setEntity(new StringEntity(params, HTTP.UTF_8));
//            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            httpClient = new HttpsUtils().new SSLClient(); // 与DefaultHttpClient httpClient = new DefaultHttpClient(); enableSSL(httpClient); 等价
            // DefaultHttpClient httpClient = new DefaultHttpClient();
            // enableSSL(httpClient);
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity httpEntity = response.getEntity();
            respMsg = EntityUtils.toString(httpEntity, "utf-8");

            log.info("发送HTTPS的post请求获取到的响应为" + respMsg);
        } catch (Exception e) {
            log.error("发送HTTPS的post请求异常", e);
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
//        post.setEntity(urlEncodedFormEntity);

        return respMsg;
    }


    /**
     * 访问https的网站
     *
     * @param httpclient
     */
    public static void enableSSL(DefaultHttpClient httpclient) {
        TrustManager[] truseAllManager = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        //调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, truseAllManager, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 4433);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //用于进行Https请求的HttpClient
    class SSLClient extends DefaultHttpClient {
        public SSLClient() throws Exception {
            super();
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {
                }

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

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = this.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        }
    }

}
这篇关于Java使用实现无验证书的HTTPS请求的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!