本文介绍了HttpClient ThreadSafeClientConnManager抛出“连接重置”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以两种不同的方式定义HttpClient:
1. Plain vanilla:client = new DefaultHttpClient();
2.线程安全:

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);
}

然后我为两种客户端类型(简单的GET请求)运行相同的JUnit测试。 #1总是正常运行,#2总是因java.net.SocketException:Connection reset而失败。调试/堆栈跟踪输出可以(虚构网站)

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)

我永远不会有机会对实体对象做任何事情,因为客户端#stage call会抛出错误。我在这里做错了什么?

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?

推荐答案

啊哈!原因是用错误的套接字工厂定义HTTPS。它应该是SSLSocketFactory

Aha! The reason was in defining HTTPS with wrong socket factory. It should be SSLSocketFactory

SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
registry.register(new Scheme("https", sslSocketFactory, 443));

这篇关于HttpClient ThreadSafeClientConnManager抛出“连接重置”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 03:06