45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 电脑教程 > 阅读资讯:SSL HTTPS访问的类的详细介绍

SSL HTTPS访问的类的详细介绍

2016-08-30 06:49:04 来源:www.45fan.com 【

SSL HTTPS访问的类的详细介绍

import javax.net.ssl.*;

import java.io.*;

import java.net.*;


public class ssltest {

protected String connect(String host,String parameter) throws Exception {

trustAllHttpsCertificates();

HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {

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

return true;
}
};

HttpsURLConnection.setDefaultHostnameVerifier(hv);

URL url = new URL(host);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
OutputStream os = urlConn.getOutputStream();
os.write(parameter.getBytes());
os.flush();
os.close();

InputStream is = urlConn.getInputStream();

byte[] buf = new byte[100];
is.read(buf);
System.out.println(new String(buf));
return "";

}

public static void main(String[] args){
try {
//参数1:连接地址 参数2:POST数据
new ssltest().connect("https://localhost/test.jsp","test1=test1&test2=test2");
} catch (Exception ex) {
ex.printStackTrace();
}
}

private static void trustAllHttpsCertificates() throws Exception {

// Create a trust manager that does not validate certificate chains:

javax.net.ssl.TrustManager[] trustAllCerts =
new javax.net.ssl.TrustManager[1];

javax.net.ssl.TrustManager tm = new miTM();

trustAllCerts[0] = tm;

javax.net.ssl.SSLContext sc =
javax.net.ssl.SSLContext.getInstance("SSL");

sc.init(null, trustAllCerts, null);

javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());

}

public static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) throws
java.security.cert.CertificateException {
return;
}

public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) throws
java.security.cert.CertificateException {
return;
}
}

}

 

本文地址:http://www.45fan.com/dnjc/69548.html
Tags: 转贴 ssl HTTPS
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部