我用2种不同的方式定义HttpClient:
1.普通香草:client = new DefaultHttpClient();
2.线程安全:
DefaultHttpClient getThreadSafeHttpClient() {
HttpParams params = new BasicHttpParams();
params
.setParameter(
"http.useragent",
"Mozilla/5.0 (Linux; U; Android 1.1; en-us;dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2");
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", PlainSocketFactory.getSocketFactory(), 443));
final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params,
registry);
return new DefaultHttpClient(manager, params);
}
然后,我对两种客户端类型(简单的GET请求)运行相同的JUnit测试。 #1始终运行良好,#2始终失败,并显示“ java.net.SocketException:连接重置”。调试/堆栈跟踪输出可以是seen here(虚拟站点)
我从来没有机会对实体对象做任何事情,因为在client#execute调用中抛出了错误。我在做什么错呢?
最佳答案
啊哈!原因是使用错误的套接字工厂定义了HTTPS。应该是SSLSocketFactory
SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
registry.register(new Scheme("https", sslSocketFactory, 443));
关于java - HttpClient ThreadSafeClientConnManager引发“连接重置”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1342681/