通用http、https访问工具类

来源:互联网 发布:中学生免费辅导软件 编辑:程序博客网 时间:2024/06/04 19:20
 

通用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;
        }

}
原创粉丝点击