我使用启用了 Https 的服务从服务器获取数据。在这里,我使用自签名方法来创建 httpClient。应用程序工作正常,但有时我得到 IOExcetion 并且我的 api 调用失败。我无法从服务器获取数据。我为我的 httpClient 使用了 ConnectionTimeOut、SocketTimeouts。我不知道为什么我的 api 调用在某些情况下会失败。请建议我在使用 https:// api 调用时避免 IOException。
在这里,我附上了我的农奴签名过程的代码。
SSLFactory 类:
public class MySSLSocketFactory extends SSLSocketFactory{
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
我的 httpClient 对象方法如下:
public HttpClient getNewHttpClient(boolean containsTimeout) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
if(containsTimeout)
{
int timeout = 60000;
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, timeout);
}
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 8443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
我的api调用方法是
HttpClient httpclient = getNewHttpClient(true);
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type", "text/xml");
BasicHttpResponse httpResponse = null;
httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
InputStream is = httpResponse.getEntity().getContent();
在上面的代码中是(InputStream)是我的最终结果。
我在 10 次迭代中至少有 2 次没有得到最终结果。请告诉我如何避免 IOException。
提前致谢。