问题
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?
回答1:
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));
来源:https://stackoverflow.com/questions/1342681/httpclient-threadsafeclientconnmanager-throws-connection-reset