Skip to content

Instantly share code, notes, and snippets.

@dedeibel
Created July 18, 2013 18:28
Show Gist options
  • Save dedeibel/6031700 to your computer and use it in GitHub Desktop.
Save dedeibel/6031700 to your computer and use it in GitHub Desktop.
Demonstrate working pool behavior for apache http
package getmultiple;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
public class Native {
public static void main(String args[]) {
System.out.println("Initializing.");
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
cm.setMaxTotal(4);
cm.setDefaultMaxPerRoute(2);
HttpClient httpClient = new DefaultHttpClient(cm);
try {
System.out.println("ready set go!");
process(new HttpGet("http://www.heise.de/thema/E_Book"), httpClient);
process(new HttpGet("http://www.heise.de/thema/Playstation-4"), httpClient);
process(new HttpGet("http://www.heise.de/thema/Google-Glass"), httpClient);
process(new HttpGet("http://www.heise.de/thema/PRISM"), httpClient);
process(new HttpGet("http://www.heise.de"), httpClient);
System.out.println("never reached.");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void process(HttpGet httpGet, HttpClient httpClient) throws IOException {
httpGet.getParams().setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 20000);
printResult(httpGet, httpClient.execute(httpGet));
}
private static void printResult(HttpGet httpGet, HttpResponse response) throws IOException {
response.getEntity().getContent().close(); // Remove this line to get halting behaviour
System.out.println(String.format("Request: %s returned with %d and %d bytes",
httpGet.getURI(), response.getStatusLine().getStatusCode(), response.getEntity().getContentLength()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment