java 调用https接口,绕过证书,使用HttpsURLCo

2020-02-27  本文已影响0人  婕烁

直接上代码,可用

第一个类:

package com.yili.test.http;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

public class SslUtil {

private static void trustAllHttpsCertificates() throws Exception { 

    TrustManager[] trustAllCerts = new TrustManager[1]; 

    TrustManager tm = new miTM(); 

    trustAllCerts[0] = tm; 

    SSLContext sc = SSLContext.getInstance("SSL"); 

    sc.init(null, trustAllCerts, null); 

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 

static class miTM implements TrustManager,X509TrustManager { 

    public X509Certificate[] getAcceptedIssuers() { 

        return null; 

    } 

    public boolean isServerTrusted(X509Certificate[] certs) { 

        return true; 

    } 

    public boolean isClientTrusted(X509Certificate[] certs) { 

        return true; 

    } 

    public void checkServerTrusted(X509Certificate[] certs, String authType) 

            throws CertificateException { 

        return; 

    } 

    public void checkClientTrusted(X509Certificate[] certs, String authType) 

            throws CertificateException { 

        return; 

    } 

/**

* 忽略HTTPS请求的SSL证书,必须在openConnection之前调用

* @throws Exception

*/ 

public static void ignoreSsl() throws Exception{ 

    HostnameVerifier hv = new HostnameVerifier() { 

        public boolean verify(String urlHostName, SSLSession session) { 

            System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); 

            return true; 

        } 

    }; 

    trustAllHttpsCertificates(); 

    HttpsURLConnection.setDefaultHostnameVerifier(hv); 

}


第二个类:

package com.yili.test;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.URL;

import java.security.GeneralSecurityException;

import java.security.NoSuchAlgorithmException;

import java.util.HashMap;

import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSocketFactory;

import javax.net.ssl.TrustManager;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.params.HttpMethodParams;

import com.yili.test.http.SslUtil;

public abstract class EM3 {

public static void main(String[] args) throws Exception {

String basePushUrl = "https://XX.XX.XX.XX/pushMessage.do";//接口地址

try {

try {

HttpClient httpClient = new HttpClient();

//设置访问编码

httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

//让服务器知道访问源为浏览器

httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1");

Map<String, String> parameters=new HashMap<String, String> ();//接口参数

parameters.put("userid", "0034523");

System.out.println(post(basePushUrl,parameters));

} catch (NoSuchAlgorithmException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (GeneralSecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static String post(String path,Map<String, String> parameters) throws Exception{

// 创建SSLContext对象,并使用我们指定的信任管理器初始化

    TrustManager[] tm = { new MyX509TrustManager() };

    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

//    SSLContext sc = SSLContext.getInstance("TLS");

// sc.init(null, trustAllCerts, new SecureRandom());

    sslContext.init(null, tm, new java.security.SecureRandom());

    // 从上述SSLContext对象中得到SSLSocketFactory对象

    SSLSocketFactory ssf = sslContext.getSocketFactory();

URL url = new URL(path);

if (parameters != null) {

url = new URL(url.toString() + buildGetParameterString(parameters));

System.out.println("url:"+url.toString() );

}

SslUtil  ssu=new  SslUtil();

ssu.ignoreSsl();

HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();

httpsConn.setRequestMethod("POST");

    httpsConn.setSSLSocketFactory(ssf);

    httpsConn.setDoInput(true);// 打开输入流,以便从服务器获取数据

    httpsConn.setDoOutput(true);// 打开输出流,以便向服务器提交数据

    httpsConn.setUseCaches(false);

    httpsConn.setInstanceFollowRedirects(true);

    httpsConn.addRequestProperty("Content-Type","application/json");

    httpsConn.addRequestProperty("Authorization","Basic RG9jdG9yWDoyMjIyMjI=");

    httpsConn.connect();

BufferedReader in = new BufferedReader(new InputStreamReader( 

        httpsConn.getInputStream())); 

        String line; 

        StringBuffer rt = new StringBuffer();

        while ((line = in.readLine()) != null) { 

            rt.append(line); 

        } 

return rt.toString();

}

private static String buildGetParameterString(Map<String, String> parameters)

{

String getParameterString = "";

for(Map.Entry<String, String> param : parameters.entrySet())

{

if(param.getValue() == null)

{

continue;

}

getParameterString += (getParameterString.length() < 1) ? ("?") : ("&");

getParameterString += param.getKey() + "=" + param.getValue();

}

return (getParameterString);

}

}


用到的jar包

apache-commons-codec-1.4.jar

commons-codec-1.13.jar

commons-httpclient-3.1.jar

commons-logging-1.2.jar

httpclient-osgi-4.5.11.jar

httpcore-4.4.13.jar

上一篇下一篇

猜你喜欢

热点阅读