Reputation: 16793
I have the following HttpConnection
call to get and parse json
object.
As you see, I am passing the proxy
inside the code as follows.
However, I need to know how could I able to get proxy
without passing it manually.
proxy= new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyString, 80));
HttpURLConnection dataURLConnection = endURL.openConnection(proxy);
dataURLConnection .setRequestProperty ("Authorization", token);
dataURLConnection .setRequestMethod("GET");
InputStream response = dataURLConnection .getInputStream();
BufferedReader reader = new BufferedReader (new InputStreamReader(response));
Upvotes: 0
Views: 597
Reputation: 1
You could set proxy host and port on jvm system property, that way you don't have to create and pass the proxy while creating a new connection.
System.setProperty("https.proxyHost", "myproxy.com");
System.setProperty("https.proxyPort", "8080");
System.setProperty("http.proxyHost", "myproxy.com");
System.setProperty("http.proxyPort", "8080");
But, keep in mind, this will affect all new connections across the JVM once the proxy is set. If you were using Spring or some other framework, they may offer you option to contextually set the proxy.
Upvotes: 0
Reputation: 146
I believe you are looking for the java.net.ProxySelector class, since 1.5.
Here's an example of it's functionality;
URI targetURI = new URI("http://stackoverflow.com/");
ProxySelector proxySelector = ProxySelector.getDefault();
List<Proxy> proxies = proxySelector.select(targetURI);
for(Proxy proxy : proxies) {
Proxy.Type proxyType = proxy.type(); //Will return a Proxy.Type (SOCKS, for example)
SocketAddress address = proxy.address(); //Returns null if no proxy is available
}
Edit: Just realized you're already using the Proxy class, so you can just use one of the resulting proxies directly in the HttpURLConnection, of course.
Upvotes: 1