提高HttpsURLConnection的性能,getInputStream()非常慢

时间:2015-11-04 07:50:05

标签: java android performance httpurlconnection

这基本上就是我如何从URL中读取内容并获取变量result中的内容。结果是json解析后。

我想知道这是否是一种提高此请求性能的方法,因为它需要4到5秒,而我希望它尽可能少于2。

事情trustAllHosts()BufferedReader br = new BufferedReader(new InputStreamReader(in));似乎需要一些时间,但我不确定。任何想法将不胜感激!

try {
        URL url;
        // get URL content
        url = new URL(apiURL);
        trustAllHosts();
        conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(DO_NOT_VERIFY);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("some values here");
        conn.setConnectTimeout(10000);

        in=conn.getInputStream();

        // open the stream and put it into BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        while ((line=br.readLine())!= null) {
            builder.append(line);
        }

        result=builder.toString();
        //System.out.print(result);
        br.close();


    } catch (MalformedURLException e) {
        result=null;
    } catch (java.net.SocketTimeoutException e) {
        result=null;
    } catch (IOException e) {
        result=null;
    }
    catch (Exception e) {
        result=null;
    }
    finally {
        try {
            in.close();
        }catch(Exception e){}
        try {
            conn.disconnect();
        }catch(Exception e){}

        return result;
    }

trustAllHosts()

/**
     * Trust every server - dont check for any certificate
     */
    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

0 个答案:

没有答案