【问题标题】:Set Socket time out in SSL Connection在 SSL 连接中设置套接字超时
【发布时间】:2017-03-17 04:55:47
【问题描述】:

您好想知道是否有办法为套接字设置超时以及在连接握手之前它所做的重试次数。我在非常糟糕的连接模式下测试了我的应用程序,并将我在 Volley 中的请求的重试策略设置为 10 秒,但 SSL 握手似乎是问题,因为它的默认超时设置为 60 秒,而 Volley 超时只得到当套接字由于尝试次数或超时而失败时触发。

这是我的方法:

private SSLSocketFactory newSslSocketFactory() {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = getApplicationContext().getResources().openRawResource(R.raw.muip);
            try {
                // Initialize the keystore with the provided trusted certificates
                // Provide the password of the keystore
                trusted.load(in, KEYSTORE_PASSWORD.toCharArray());
            } finally {
                in.close();
            }

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(trusted);



            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            SSLSocketFactory sf = new NoSSLv3Factory(context.getSocketFactory());
            HttpsURLConnection.setDefaultSSLSocketFactory(sf);





            return sf;
        } catch (Throwable e) {
            Log.e(TAG, "newSslSocketFactory: "+ e.getMessage(),e );
            throw new AssertionError(e);
        }
    }

我正在使用 Volley 来提出我的请求,我实现它的方法是:

 public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            Network network = new BasicNetwork(new HurlStack(null, newSslSocketFactory()));

            Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
            mRequestQueue = new RequestQueue(cache, network);
            mRequestQueue.start();
        }

        return mRequestQueue;
    }

我也尝试像这样设置超时:

    SSLSocketFactory sf = new NoSSLv3Factory(SSLCertificateSocketFactory.getDefault(10000, new SSLSessionCache(this)));

【问题讨论】:

    标签: java android sockets ssl android-volley


    【解决方案1】:

    mRequestQueue.start() 之后你可以这样设置超时:

    int socketTimeout = 30000;   // 30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);
    queue.add(stringRequest);
    

    【讨论】:

    • 只要阅读问题和说明,你就会知道凌空超时取决于套接字超时
    • 请仔细阅读说明。我说当他试图握手时,它不是在凌空它在 SSL 连接方面。如果仔细阅读描述,你会注意到我提到我已经在使用设置为 10 秒的重试策略,但它只会在套接字握手失败时触发
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2017-10-15
    • 2011-05-11
    • 2016-10-18
    • 2011-08-03
    • 2012-11-12
    相关资源
    最近更新 更多