Advertisement
Guest User

Java global proxy change

a guest
Dec 15th, 2017
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.net.*;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6.  
  7. public class ProxyChange {
  8.  
  9.     public static void change(List<String> ignoreHosts, String proxyAddress, int port) {
  10.  
  11.         List<String> ignore = new ArrayList<>();
  12.         for (String item : ignoreHosts) ignore.add(item.toLowerCase().trim());
  13.         Collections.sort(ignore);
  14.  
  15.         ProxySelector.setDefault(new ProxySelector() {
  16.             private final ProxySelector def = ProxySelector.getDefault();
  17.  
  18.             @Override
  19.             public List<Proxy> select(final URI uri) {
  20.                 String scheme = uri.getScheme();
  21.                 String host = uri.getHost();
  22.                 if (Collections.binarySearch(ignore, host) < 0 && (scheme.startsWith("http") || scheme.startsWith("socket") || scheme.startsWith("ftp"))) {
  23.                     return Collections.singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, port)));
  24.                 } else {
  25.                     return def.select(uri);
  26.                 }
  27.             }
  28.  
  29.             @Override
  30.             public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
  31.                 throw new UnsupportedOperationException("Not supported yet.");
  32.             }
  33.         });
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement