Search code examples
javaproxyurihttp-proxyproxyselector

ProxySelector: Different Proxy for Each URL


I'm trying to understand how the ProxySelector class works. My current code looks like this:

    URI uri = new URI("http://google.com");
    proxySelector.select(uri);

I understand that when calling proxySelector.select(uri); this is suppose to return a list of proxies for the respective URI. But I don't see how to set the proxy for each URI.

I know I could set the default proxy using the setDefault() method but as far as I understand this will set the system wide proxy, not the proxy for a specific URI.

I might be missing some basic point here but how do I set one proxy for url A (such as http://google.com) and a different proxy for url B (such as http://ebay.com) and then have the system automatically select the correct proxy each time it connects to the corresponding url?


Solution

    1. Override ProxySelector.select(URI uri) method where you implement custom logic to choose right proxy or list of proxies for the URI.

    2. either set the new, custom, ProxySelector as system wide by calling ProxySelector.setDefault(customProxySelector).

      Any subclass of URLConnection will use ProxySelector, e.g.:

      URLConnection conn = url.openConnection();
      
    3. or configure framework you are going to use to invoke remote URI, e.g Spring RestTemplate:

      HttpRoutePlanner routePlanner = new SystemDefaultRoutePlanner(new MyProxySelector());
      
      HttpComponentsClientHttpRequestFactory clientHttpRequestFactory 
          = new HttpComponentsClientHttpRequestFactory(
              HttpClientBuilder.create()
                  .setRoutePlanner(routePlanner)
                  .build());
      restTemplate = new RestTemplate(clientHttpRequestFactory);
      

    It is good practice to fallback to default ProxySelector in custom select(URI uri) in case the custom logic does not determine suitable proxy for the uri.

    See my other answer for ProxySelector example.

    Networking and proxies is well explained in Java Networking and Proxies (paragraph 4 ProxySelector) and ProxySelector Java docs.