Doing a Google Search on how to get Java’s URLConnection or HttpURLConnection to use a SOCKS proxy yields many results on how to pass in arguments to the JVM to set it up, or to call System.setProperty(), which then sets the SOCKS proxy to be used for all HTTP connections through Java. But what if you want to limit it to only certain connections started from HttpURLConnection, or if the proxy address isn’t available until later on?
Here’s a code snippet on how you’d go about doing that programatically.
String proxyString = "127.0.0.1:12345"; //ip:port String proxyAddress = proxyString.split(":"); Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyAddress, Integer.parseInt(proxyAddress))); URL url = new URL("http://some.website"); HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); //do whatever with httpUrlConnection, it will be connected through the SOCKS proxy!
And that’s it.