通用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;
}
}
相关文章推荐
- 一个爬取https和http通用的工具类
- Apache配置http访问转https(widows和linux通用)
- 在IIS里,自动把需要用https访问的http页面转换
- HTTP访问转HTTPS访问的总结--关于本地https访问以及服务器https访问配置
- centos下访问windows subversion (http、https)
- android httpClient 支持HTTPS的访问方式
- nginx强制使用https访问(http跳转到https)
- java程序访问http,或https最简单的方法
- Java 程序(httpclient) 访问https保护的网站
- 详解NGINX访问https跳转到http的解决方法
- SVN如何将版本库url访问地址中的https改为http
- ASIHTTPRequest访问https[error-9844]解决方法
- Tomcat 访问http强制 https 访问配置方法
- 网络编程HttpClient----实现Http访问工具类
- Nginx配置https和http可同时访问方法
- oracle utl_http 访问https类型
- Tomcat配置https及访问http自动跳转至https
- HTTP与HTTPS对访问速度、性能等的影响
- Nginx-配置https虚拟服务(访问http时自动跳转https)
- delphi idhttp访问https需要增加IdSSLIOHandlerSocketOpenSSL1