Created
January 18, 2018 13:09
-
-
Save michalbcz/a1d4c178b2efb1531a9b8335986959bb to your computer and use it in GitHub Desktop.
java http proxy settings programatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.io.IOUtils; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.Authenticator; | |
import java.net.InetSocketAddress; | |
import java.net.PasswordAuthentication; | |
import java.net.Proxy; | |
import java.net.SocketAddress; | |
import java.net.URL; | |
import java.net.URLConnection; | |
public class TestProxy { | |
public static void main(String[] args) throws IOException { | |
/* those properties are not reflected by Java's URLConnection */ | |
System.setProperty("http.proxyUser", "michalb"); | |
System.setProperty("http.proxyPassword", "password"); | |
/* this is needed for authentication in case of Java's URLConnection */ | |
Authenticator.setDefault(new Authenticator() { | |
@Override | |
protected PasswordAuthentication getPasswordAuthentication() { | |
if (getRequestorType() == RequestorType.PROXY) { | |
String prot = getRequestingProtocol().toLowerCase(); | |
String host = System.getProperty(prot + ".proxyHost", ""); | |
String port = System.getProperty(prot + ".proxyPort", ""); | |
String user = System.getProperty(prot + ".proxyUser", ""); | |
String password = System.getProperty(prot + ".proxyPassword", ""); | |
return new PasswordAuthentication(user, password.toCharArray()); | |
} | |
return null; | |
} | |
}); | |
SocketAddress addr = new InetSocketAddress("some.proxy.address.com", 8080); | |
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); | |
URL url = new URL("http://www.jsbin.com"); | |
URLConnection conn = url.openConnection(proxy); | |
InputStream inputStream = conn.getInputStream(); | |
System.out.println(IOUtils.toString(inputStream)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment