您的位置:首页 > 理论基础 > 计算机网络

通用http、https访问工具类

2011-08-09 10:21 881 查看

通用http、https访问工具类

对于https的访问,需要信任服务器端的证书。

public class HttpHelper{

public static HttpURLConnection getConnection(String urlStr) throws KeyManagementException, MalformedURLException, NoSuchAlgorithmException, IOException{

HttpURLConnection conn = null;

if (urlStr.toLowerCase().startsWith("https"))

conn = getHttpsConnection(urlStr);

else

conn = getHttpConnection(urlStr);

return conn;

}

private static HttpURLConnection getHttpConnection(String urlStr) throws MalformedURLException, IOException {

URL url = new URL(urlStr);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

return conn;

}

private static HttpsURLConnection getHttpsConnection(String urlStr) throws MalformedURLException, IOException,NoSuchAlgorithmException, KeyManagementException {

URL url = new URL(urlStr);

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

conn.setHostnameVerifier(new IgnoreHostnameVerifier());

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

SSLContext sslContext = SSLContext.getInstance("TLS");

sslContext.init(null, tm, null);

SSLSocketFactory ssf = sslContext.getSocketFactory();

conn.setSSLSocketFactory(ssf);

return conn;

}

}

public class IgnoreCertificationTrustManger implements X509TrustManager {

private X509Certificate[] certificates;

public void checkClientTrusted(X509Certificate certificates[],

String authType) throws CertificateException {

if (this.certificates == null) {

this.certificates = certificates;

}

}

public void checkServerTrusted(X509Certificate[] ax509certificate, String s)

throws CertificateException {

if (this.certificates == null) {

this.certificates = ax509certificate;

}

}

public X509Certificate[] getAcceptedIssuers() {

return null;

}

}

public class IgnoreHostnameVerifier implements HostnameVerifier{

public boolean verify(String arg0, SSLSession arg1) {

return true;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: