Following utility class helps you to get the details of current proxy state.
ProxyUtil.java
package com.sample.app.net;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
public class ProxyUtil {
private URI uriToConnect;
public static final String DEFAULT_URI = "https://self-learning-java-tutorial.blogspot.com";
public ProxyUtil(String uriToConnect) {
try {
this.uriToConnect = new URI(uriToConnect);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public ProxyUtil() {
this(DEFAULT_URI);
}
@Override
public String toString() {
ProxySelector proxySelector = ProxySelector.getDefault();
StringBuilder result = new StringBuilder();
for (Proxy proxy : proxySelector.select(uriToConnect)) {
SocketAddress address = proxy.address();
// address is null for a direct connection.
if (address == null) {
result.append("Direct connection\n");
continue;
}
result.append(proxy);
if (!(address instanceof InetSocketAddress)) {
result.append("[");
result.append("Not an instance of InetSocketAddress");
result.append("]\n");
continue;
}
InetSocketAddress ina = (InetSocketAddress) address;
result.append(' ');
result.append(ina.getHostName());
result.append(':');
result.append(ina.getPort());
if (ina.isUnresolved()) {
result.append(" [unresolved]\n");
continue;
}
InetAddress addr = ina.getAddress();
result.append(" [");
result.append(addr.getHostAddress());
result.append("]\n");
continue;
}
return result.toString();
}
}
ProxyUtilDemo.java
package com.sample.app.net;
public class ProxyUtilDemo {
public static void main(String[] args) {
System.out.println(new ProxyUtil());
}
}
No comments:
Post a Comment