返回通用认证的HttpConnection对象

最近项目在访问服务器时出现了证书过期问题,需要使用无认证的连接来向服务器请求数据,方法如下:

public static HttpURLConnection prepareConnection(
            String serverUrl) throws IOException, MalformedURLException, ProtocolException {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (GeneralSecurityException e) {
        }
        // Now you can access an https URL without having the certificate in the
        // truststore
        URL url = new URL(serverUrl);
        HttpURLConnection urlConnection = null;
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setConnectTimeout(Constants.TIMEOUT_4_CONN);      // 设置连接主机超时
        urlConnection.setReadTimeout(Constants.TIMEOUT_4_READ);         // 设置读取数据超时
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.connect();                                        // 打开连接
        return urlConnection;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值