【发布时间】: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