HttpClient ThreadSafeClientConnManager抛出“连接重置”

时间:2009-08-27 17:47:56

标签: java httpclient socketexception

我以两种不同的方式定义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:Connection reset”而失败。调试/堆栈跟踪输出可以是seen here(虚构站点)

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

1 个答案:

答案 0 :(得分:2)

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

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