桥山之巅,姬水之畔

Java发送Https请求(跳过证书验证)-旧版

2021.01.05

此代码已过时,请移步新版代码最新代码

依赖

 <dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.5.5</version>
 </dependency>
 <dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpmime</artifactId>
 <version>4.5.13</version>
 </dependency>
 <dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>fastjson</artifactId>
 <version>1.2.47</version>
 </dependency>

代码

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.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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;


/**
 * Description:  过时的https请求方法 <br>
 * date:  2020/12/30 0:10 <br>
 * author:  andus.top <br>
 * logic:
 */
public class OldHttps {
    public static void main(String[] args) throws Exception {
        rhptPost();
    }

    /**
     * 融合平台post调用示例
     */
    public static void rhptPost() throws Exception {
        HttpPost post = new HttpPost("https://xxxxxxxx");
        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();
        jsonObject.put("paramA","xxxxxxx");
        jsonObject.put("paramB","123");
        List<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("jsonData",jsonObject.toString()));
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, HTTP.UTF_8);
        post.setEntity(urlEncodedFormEntity);

        SSLClient httpClient = new OldHttps().new SSLClient(); // 与DefaultHttpClient httpClient = new DefaultHttpClient(); enableSSL(httpClient); 等价
        // DefaultHttpClient httpClient = new DefaultHttpClient();
        // enableSSL(httpClient);
        CloseableHttpResponse response = httpClient.execute(post);
        HttpEntity httpEntity = response.getEntity();
        String string = EntityUtils.toString(httpEntity, "utf-8");
        System.out.println(string);
    }


    /**
     * 访问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));
        }
    }
}