您想知道是否有一种方法可以为套接字设置超时,以及在连接获得握手之前它执行的重试次数。我在非常糟糕的连接模式下测试了我的应用程序,并且我在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)));
答案 0 :(得分:-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);