问题
I am working on an Android application and I am using various libraries like Picaso, Retrofit, Crashlytics, etc. and my college WIFI have proxy on it.
I know how to use a proxy when sending a HTTP requests to a server, but all the libraries that I am using have there own HTTP requests, so overriding all their HTTP classes would be a headache, and I am not even sure how to do that.
So, is there a way to route all the traffic of the App through a proxy (when available), like any library or some HTTP request overriding all the outgoing requests.
回答1:
I implemented this as below. (I forgot the original source).
import java.net.Proxy;
import java.net.ProxySelector;
//setting Application-Wide proxy Values
private void setProxy() {
//Device proxy settings
ProxySelector defaultProxySelector = ProxySelector.getDefault();
Proxy proxy = null;
List<Proxy> proxyList = defaultProxySelector.select(URI.create("http://www.google.in"));
if (proxyList.size() > 0) {
proxy = proxyList.get(0);
Log.d("proxy", String.valueOf(proxy));
try {
String proxyType = String.valueOf(proxy.type());
//setting HTTP Proxy
if (proxyType.equals("HTTP")) {
String proxyAddress = String.valueOf(proxy.address());
String[] proxyDetails = proxyAddress.split(":");
String proxyHost = proxyDetails[0];
String proxyPort = proxyDetails[1];
Log.d("proxy", proxyType + " " + proxyHost + " " + proxyPort);
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Put this method in your base activity's onCreate method so it will get executed everytime user opens the application.
回答2:
You can redirect specific network traffic (on a per application basis) as per the following link.
Network traffic via Proxy
来源:https://stackoverflow.com/questions/37687332/redirect-all-network-of-android-app-which-is-using-libraries-through-a-proxy-n