Java实现免证书访问Https请求

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/rexueqingchun/article/details/86686761

创建证书管理器类

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/** 
 * 证书信任管理器(用于https请求) 
 * 
 */
public class MyX509TrustManager implements X509TrustManager {

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

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

	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}

服务器主机名校验类

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class NullHostNameVerifier implements HostnameVerifier{
	
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

调用测试

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import cn.com.goevent.weixin.util.MyX509TrustManager;

public class HttpsTest {

	public static void main(String[] args) throws Exception {	
	    //设置可通过ip地址访问https请求
	    HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
	    TrustManager[] tm = {new MyX509TrustManager()}; 
	    SSLContext sslContext = SSLContext.getInstance("TLS"); 
	    sslContext.init(null, tm, new java.security.SecureRandom());  
	    // 从上述SSLContext对象中得到SSLSocketFactory对象  
	    SSLSocketFactory ssf = sslContext.getSocketFactory();
    	    String urlStr = "https://192.168.1.10/login_queryLkBySfmc.htm";
    	    URL url = new URL(urlStr);
	    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
	    con.setSSLSocketFactory(ssf); 
    	    con.setRequestMethod("POST"); // 设置以POST方式提交数据
    	    con.setDoInput(true); // 打开输入流,以便从服务器获取数据
    	    con.setDoOutput(true);// 打开输出流,以便向服务器提交数据
	    //设置发送参数
            String param = "sfmc=测试";
            PrintWriter out = new PrintWriter(new OutputStreamWriter(con.getOutputStream(),"UTF-8"));
            out.print(param);          
            out.flush();
            out.close();
            //读取请求返回值
	    InputStreamReader in = new InputStreamReader(con.getInputStream(),"UTF-8");
	    BufferedReader bfreader = new BufferedReader(in);
	    String result = "";
	    String line = "";
	    while ((line = bfreader.readLine()) != null) {
	    	result += line;
	    }
	    System.out.println("result:"+result);    
	}
}

 

展开阅读全文

没有更多推荐了,返回首页