vendredi 9 décembre 2011

How to use Apache HttpClient with JVM proxy settings ?

I usualy try to stay close to sitebricks core functionnality. When I faced the issue of accessing a distant website threw a post request, I tried to use sitebricks webclient as described on official website :


The current version is not ready to use as it doesn't support proxy (or at least I didn't find how to make in work) and also HTTPS request.
After a few search on google, I started to use Apache HttpClient, part of HttpComponents.
I notice that this implementation is not taking care of proxy settings in the JVM. I did that function to use them anyway.
Please notice that my final goal was to use a HTTPS distant website.

private DefaultHttpClient initHttpClient() {
  
  DefaultHttpClient client = new DefaultHttpClient();
  
  String proxyHost = System.getProperty("https.proxyHost");
  if(proxyHost == null) {
   proxyHost = System.getProperty("http.proxyHost");
  }
  
  if(proxyHost != null) {
   
   String proxyUser = System.getProperty("https.proxyUser");
   if(proxyUser == null) {
    proxyUser = System.getProperty("http.proxyUser");
   }
   
   String proxyPassword = System.getProperty("https.proxyPassword");
   if(proxyPassword == null) {
    proxyPassword = System.getProperty("http.proxyPassword");
   }
   
   if(proxyUser != null && proxyPassword != null) {
    client.getCredentialsProvider().setCredentials(
                     new AuthScope("localhost", 8080), 
                     new UsernamePasswordCredentials(proxyUser, proxyPassword));
   }
   
   String proxyPort = System.getProperty("https.proxyPort");
   if(proxyPort == null) {
    proxyPort = System.getProperty("http.proxyPort");
   }
   if(proxyPort == null) {
    proxyPort = "80";
   }
   
   HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
            
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
  }
  
  return client;

Finaly really easy to do.

0 commentaires:

Enregistrer un commentaire