Using a ProxySelector

Here’s a working example that says everything. MyProxySelector is automatically contacted when URLConnection is about to make a connection.

Main.java:

import java.net.*;
import java.io.*;
import java.util.*;

public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <URL>");
         System.exit(0);
      }
      
      System.out.println("Old ProxySelector: " + ProxySelector.getDefault());
      ProxySelector.setDefault(new MyProxySelector());
      System.out.println("New ProxySelector: " + ProxySelector.getDefault());
          
      URL url = new URL(args[0]);
      URLConnection connection = url.openConnection();
 
      connection.setConnectTimeout(5000);
      connection.connect();
   }
}

class MyProxySelector extends ProxySelector
{
   public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
      System.out.println("connectFailed: " + ioe.getMessage());
   }
   
   public List<Proxy> select(URI uri) {
      ArrayList<Proxy> list = new ArrayList<Proxy>();
      Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.esus.com", 8080));
      list.add(proxy);

      return list;
   }
}