HttpClient ThreadSafeClientConnManager 抛出“连接重置”
我用两种不同的方式定义 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);
}
然后我对两种客户端类型运行相同的 JUnit 测试(简单的 GET 请求)。 #1 总是运行良好,#2 总是失败并显示“java.net.SocketException:连接重置”。调试/stacktrace 输出可以在这里看到(虚构的网站)
我从来没有得到过由于在 client#execute 调用中抛出错误,因此有机会对实体对象执行任何操作。我在这里做错了什么?
I define HttpClient in 2 different ways:
1. Plain vanilla: client = new DefaultHttpClient();
2. Thread safe:
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);
}
Then I run same JUnit test for both client types (simple GET request). #1 always runs fine, #2 always fails with "java.net.SocketException: Connection reset". Debug/stacktrace output can be seen here (fictitious site)
I never get a chance to do anything with entity object since error is thrown at client#execute call. What's I'm doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
啊哈!原因是使用错误的套接字工厂定义 HTTPS。应该是 SSLSocketFactory
Aha! The reason was in defining HTTPS with wrong socket factory. It should be SSLSocketFactory