TL;DR: There's no easy way to create a proxy :)
I've tried for a while to build a way to request something through a proxy, for testing an emulated android app. The solution came from Octavian who kindly provided me a snippet to run once per app lifetime. It tackles the problem from two fronts:
- Sets proxy system properties (
http.proxy*
andhttps.proxy*
) - Sets the default
Authenticator
The code is:
public class ProxyUtils {
public static void authenticate() {
// Bypass on a certain host
try {
if (!InetAddress.getLocalHost().toString().toLowerCase().contains("local")) {
return;
}
} catch (UnknownHostException e) {
getLogger(ProxyUtils.class.getName()).log(SEVERE, null, e);
return;
}
// System properties
setProperty("http.proxyHost", "192.168.0.110"); // your proxy IP
setProperty("http.proxyPort", "88"); // your proxy port
setProperty("http.proxyUser", "user");
setProperty("http.proxyPassword", "password");
setProperty("https.proxyHost", getProperty("http.proxyHost"));
setProperty("https.proxyPort", getProperty("http.proxyPort"));
setProperty("https.proxyUser", getProperty("http.proxyUser"));
setProperty("https.proxyPassword", getProperty("http.proxyPassword"));
// Authenticator
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password".toCharArray());
}
});
}
}
One thing that can be improved would be a configuration-based (e.g. defined environment variable) bypass code, rather than a hostname approach.
and the full code (with imports and such) is in this Gist:
NOTE: All credit goes to Tavi for finding and building this.
HTH,
Member discussion: