微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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));
        }
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐