Fabien Benoit-Koch
Fabien Benoit-Koch

Reputation: 2841

How to set global http proxy settings for apache HttpClient

In Apache Commons 4.3 and onwards, you need to inject your HTTP proxy settings at the HttpRequest level - but not globally, in the HttpClient itself:

RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet httpget = new HttpGet("http://url");
httpget.setConfig(config);
...

httpclient.execute(target, httpget);

The problem is that, in some higher-level libraries, configuration is made by passing a custom-built HttpClient instance. But that doesn't give you access to the HttpRequest built inside the API code.

For instance, in Jolokia (a JMX REST bridge), you create your client like this:

J4pClient j4pClient = new J4pClient("http://localhost:8080/jolokia", httpClient);

Is there a way to specify an HTTP proxy in this case ? The http.proxyHost system property seems ignored and i'd like to avoid creating a full layer of wrapper classes around HttpClient and HttpRequest to inject the settings during the request creation.

Upvotes: 4

Views: 8917

Answers (1)

wshuman3
wshuman3

Reputation: 141

You can use HttpClientBuilder. It will pull in the system properties for http.proxyHost, http.proxyPort, http.nonProxyHosts.

HttpClientBuilder.create().useSystemProperties().build();

See http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html

Upvotes: 9

Related Questions