Search code examples
javahttpapache-commons-httpclient

How to set proxy host on HttpClient request in Java


I want to set proxy before sending HttpClient request on a URL. As I am able to connect it curl command setting up the proxy but with Java code I am not able to do that.

Curl command:

**curl -I -x IP:80  URL**

Code change done in java file:

HttpClient client = new HttpClient();
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));

With above code changes in my java file I am getting below error :

java.net.ConnectException: Connection refused (Connection refused)

Which shows that I am not able to connect that URL with the proxy I am trying to use to connect the URL.


Solution

  • I think this could be helpful:

    HttpClient client = new HttpClient();
    
    HostConfiguration config = client.getHostConfiguration();
    config.setProxy("someProxyURL", "someProxyPort");
    
    Credentials credentials = new UsernamePasswordCredentials("username", "password");
    AuthScope authScope = new AuthScope("someProxyURL", "someProxyPort");
    client.getState().setProxyCredentials(authScope, credentials);
    
    EntityEnclosingMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));