Apache HTTPClient does not make more than 2 connections - java

I've been trying to implement connection pooling for my application using Apache HTTPClient (v4.1). The problem is that the client always makes only two connections when run, though there are enough threads running parallel. I have been trying to modify the code for a while now, but nothing has helped yet.
I'm using ThreadSafeClientConnManager for connection pooling and set the MaxTotal and DefaulMaxPerRoute to values I want.
Is there anything that comes to your mind first that I might want to check?
Here's that code segment that I use to create the client.
DefaultHttpClient createClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(60000));
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(60000));
params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", sf, 6443));
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
cm.setMaxTotal(2 * maxConnections);
cm.setDefaultMaxPerRoute(maxConnections);
HttpHost localhost = new HttpHost("localhost");
cm.setMaxForRoute(new HttpRoute(localhost), maxConnections);
HttpHost sdpTargetHost = new HttpHost("webserviceIP", webservicePort, "https");
cm.setMaxForRoute(new HttpRoute(sdpTargetHost, null, true), maxConnections);
return new DefaultHttpClient(cm, params);
}
The client returned by this function is used in Runnables managed by a ThreadPoolExecutor. The Runnables use the client, and has these lines:
HttpResponse response = httpClient.execute(httpPost, context);
HttpEntity entity = response.getEntity();
....
EntityUtils.consume(entity);
From what I know, the EntityUtils.consume(entity) will notify the connection manager that the connection is no longer used, and thus will release the connection to be used by other threads. So I'm guessing the connection management is alright.
I guess I've provided enough info, please tell me if I'm to add anything more.
Thanks

OK. I've found the solution, thanks to oleg for pointing out the logging, and to google and all the forums. All I had to do was define the class with only the connection manager, and then set HttpParams using HttpClient.setParams(). So the code will look something like this:
DefaultHttpClient createClient() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", sf, 6443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);
cm.setMaxTotal(maxConnections);
cm.setDefaultMaxPerRoute(maxConnections);
HttpHost targetHost = new HttpHost("webserviceIP", webservicePort, "https");
cm.setMaxForRoute(new HttpRoute(targetHost, null, true), maxConnections);
return new DefaultHttpClient(cm);
}
And right before using the client,
DefaultHttpClient httpClient = createClient();
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(60000));
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(60000));
params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
httpClient.setParams(params);
There apparently is no difference in the code logically, but this fixed my problem. I presume this probably is some sorta bug in the HttpClient 4.1 API.

I was not able to set this option in cm
cm.setDefaultMaxPerRoute(maxConnections);
It was necessary to do so:
ConnPerRoute perRoute = new ConnPerRouteBean(100);
ConnManagerParams.setMaxConnectionsPerRoute(params, perRoute);
ConnManagerParams.setMaxTotalConnections(params, 100);
ConnManagerParams.setTimeout(params, 15000);

Related

Securing a connection checking SSL Certificate?

I'm doing an internships.
Here they give me a code of an Android application that have been revisione by an agency for the code security and told me to change some points present in a document.
Now they fear for the information leakage because the application doesn't check for the SSL certificates when connecting to the bank server, risking a "Man In The Middle" attack.
Is there any class that i can use to check expirency date of the cert. or if it is trusted?
An example of a http connection in the app:
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams bhttpparams = new BasicHttpParams();
HttpProtocolParams.setVersion(bhttpparams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(bhttpparams, "utf-8");
bhttpparams.setBooleanParameter("http.protocol.expect-continue", false);
HttpConnectionParams.setConnectionTimeout(bhttpparams, 20000);
HttpConnectionParams.setSoTimeout(bhttpparams, 200000);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(bhttpparams, registry);
client = new DefaultHttpClient(ccm, bhttpparams);
client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials("", ""));
HttpResponse response = client.execute(urlws);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
The vulnerability is here. Remove it.
But I would question both the competence and the sanity of anyone who gave this task to an uninformed intern without a proper briefing, and you can tell them I said so. I would also be asking some severe questions about how this line of code ever got there in the first peace, and about the inadequacy of the testing that allowed it to remain.

HttpClient 4.3.x, fixing deprecated code to use current HttpClient implementations

I had the following code, which still compiles, but they're all deprecated:
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager clientConnectionManager = base.getConnectionManager();
SchemeRegistry schemeRegistry = clientConnectionManager.getSchemeRegistry();
schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));
return new DefaultHttpClient(clientConnectionManager, base.getParams());
I tried my best to replace it with this portion of the code:
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setConnectionManager(new BasicHttpClientConnectionManager());
builder.setSSLSocketFactory(sslConnectionFactory);
return builder.build();
As you can see, there are few lines of code from the top post that I don't know how to include on the new portion. How can I add needed code, such as, an alternate SchemeRegistry?
I can not comment yet, but here is a small upgrade to herau's answer since it's deprecated since 4.4, maybe someone will find it useful.
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslConnectionFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionFactory)
.build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
return builder.build();
As manual said, I have replaced library to NoopHostnameVerifier and use it like that:
private static CloseableHttpClient client =
HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

Is the ProxyFactory replacement in RESTEasy thread safe?

I developed a service in RESTEasy using ProxyFactory and ClientExecutor like this:
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
MyClass client = ProxyFactory.create(MyClass.class, "http://www.example.com", clientExecutor);
It always worked perfectly. After RESTEasy deprecated both ClientExecutor and ProxyFactory, they provided a new ResteasyClient for external connections, but I don't know if this new ResteasyClient is threadsafe. This is the new sample code from the documentation:
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://example.com/base/uri");
SimpleClient simple = target.proxy(SimpleClient.class);
UPDATE: I used the code with the ResteasyClient and I got many of these errors:
javax.ws.rs.ProcessingException: Unable to invoke request
Caused by
java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated. Make sure to release the connection before allocating another one.
We use this:
final ResteasyClient client = new ResteasyClientBuilder()
.connectionPoolSize(10)
.maxPooledPerRoute(5)
.build();
And after debugging I found out that (at least in our situation) the RESTEasy client uses the ThreadSafeClientConnManager by default so I think there is no need to specify a different one although according to the JavaDoc it is deprecated in favour of PoolingHttpClientConnectionManager (note the extra Http). But this has been fixed in RESTEasy client 3.0.5.Final: https://issues.jboss.org/browse/RESTEASY-948
It's a jungle of HTTP connection managers out there..
This worked for me. Just needed to find the hook into setting up the Apache HTTP engine. Mostly based on RestEasy 3.0.5.Final API
public static Object setupServiceProxy(#NotNull Class responseClass) {
ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
ResteasyClientBuilder builder = new ResteasyClientBuilder().providerFactory(factory);
ResteasyClient client = builder.httpEngine(setupHttpDefaults()).build();
ResteasyWebTarget target = client.target(url);
return target.proxy(responseClass);
}
public static ClientHttpEngine setupHttpDefaults() {
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 30000);
HttpConnectionParams.setSoTimeout(params, 30000);
BasicHttpContext localContext = new BasicHttpContext();
return new ApacheHttpClient4Engine(httpClient, localContext);
}

Apache httpclient makes lots of connections

I'm using apache httpclient 4.0 to connect to a video stream (motion jpeg) over http. Here's my code:
DefaultHttpClient client;
HttpParams params = new BasicHttpParams();
List<String> authpref = new ArrayList<String>();
authpref.add(AuthPolicy.DIGEST);
authpref.add(AuthPolicy.BASIC);
params.setParameter("http.auth.proxy-scheme-pref", authpref);
params.setParameter("http.protocol.handle-authentication", Boolean.TRUE);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ClientConnectionManager connectionManager =
new ThreadSafeClientConnManager(params, schemeRegistry);
client = new DefaultHttpClient(connectionManager, params);
client.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password));
HttpResponse videoResponse = client.execute(new HttpGet(url));
The problem is that the client.execute() line seems to make hundreds of connections to the video stream. I can see this by logging onto the server and doing a netstat: there's an enourmous number of connections to port 80 and they're all stuck in the TIME_WAIT state.
Am I doing something wrong here? What's going on?
Thanks for the help.
That's what happens if you do not release connections back to the pool and / or create a new connection pool for each and every request.
http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/connmgmt.html

Http authentication with apache httpcomponents

I am trying to develop a java http client with apache httpcomponents 4.0.1. This client calls the page "https://myHost/myPage". This page is protected on the server by a JNDIRealm with a login form authentication, so when I try to get https://myHost/myPage I get a login page. I tried to bypass it unsuccessfully with the following code :
//I set my proxy
HttpHost proxy = new HttpHost("myProxyHost", myProxyPort);
//I add supported schemes
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
supportedSchemes.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// prepare parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
supportedSchemes);
DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
//I add my authentication information
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("myHost/myPage", 443),
new UsernamePasswordCredentials("username", "password"));
HttpHost host = new HttpHost("myHost", 443, "https");
HttpGet req = new HttpGet("/myPage");
//show the page
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String rsp = httpClient.execute(host, req, responseHandler);
System.out.println(rsp);
When I run this code, I always get the login page, not myPage. How can I apply my credential parameters to avoid this login form?
Any help would be fantastic
HttpClient doesn't support form login. What you are trying to do is Basic Auth, which does't work with form login.
You can simply trace the form post for login page and send the POST request from HttpClient.

Categories