javaapache-httpcomponentsapache-httpclient-5.x

How to set proxy for individual requests in Apache HttpClient 5?


I would like to configure an HTTP proxy for some individual requests and not for others, using Apache HttpClient 5. However it looks like RequestConfig.Builder.setProxy() is deprecated. The javadoc suggests using HttpRoutePlanner, but it looks like this operates at the global HttpClient level, not at the request level.

Is there a way in HttpClient 5 to configure the proxy at the request level?


Solution

  • One of the arguments to HttpRoutePlanner's determineRoute method is the HttpContext. You can use that, especially if you extend DefaultRoutePlanner and override its determineProxy method, because this is part of the (current) determineRoute implementation:

    HttpHost proxy = config.getProxy();
    if (proxy == null) {
        proxy = determineProxy(host, context);
    }
    

    For each request you can now explicitly create an HttpContext, set the proxy host as attribute, and then use your custom DefaultRoutePlanner sub class to extract that proxy from the HttpContext.

    That does mean you need to explicitly configure the proxy for each request separately though.