检查 Web 代理的类型
Posted
技术标签:
【中文标题】检查 Web 代理的类型【英文标题】:Checking the type of a web proxy 【发布时间】:2011-07-21 08:59:50 【问题描述】:如何判断一个网络代理 IP 是 HTTP 类型还是 SOCKS4/5 类型的 java?
谢谢。
【问题讨论】:
【参考方案1】:正如我在另一个答案中的 cmets 中所提到的,如果您知道代理服务器的 IP 地址并想检测它是什么类型,您可以尝试 Java 中的每种代理类型,直到其中一种有效为止。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
public class ProxyTest
public static void main(String... args)
throws IOException
InetSocketAddress proxyAddress = new InetSocketAddress("myproxyaddress", 1234);
Proxy.Type proxyType = detectProxyType(proxyAddress);
System.out.println(proxyAddress + " is a " + proxyType + " proxy.");
public static Proxy.Type detectProxyType(InetSocketAddress proxyAddress)
throws IOException
URL url = new URL("http://www.google.com");
List<Proxy.Type> proxyTypesToTry = Arrays.asList(Proxy.Type.SOCKS, Proxy.Type.HTTP);
for (Proxy.Type proxyType : proxyTypesToTry)
Proxy proxy = new Proxy(proxyType, proxyAddress);
//Try with SOCKS
URLConnection connection = null;
try
connection = url.openConnection(proxy);
//Can modify timeouts if default timeout is taking too long
//connection.setConnectTimeout(1000);
//connection.setReadTimeout(1000);
connection.getContent();
//If we get here we made a successful connection
return(proxyType);
catch (SocketException e) //or possibly more generic IOException?
//Proxy connection failed
//No proxies worked if we get here
return(null);
在此代码中,它首先尝试使用带有 SOCKS 的 myproxyaddress 上的代理连接到 www.google.com,如果失败,它将尝试将其用作 HTTP 代理,返回有效的方法,如果没有,则返回 null工作。
【讨论】:
【参考方案2】:如果您想确定从 Java 中使用的代理类型,可以使用 ProxySelector 和 Proxy。
例如
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.List;
public class ProxyTest
public static void main(String... args)
System.setProperty("java.net.useSystemProxies", "true");
List<Proxy> proxyList = ProxySelector.getDefault().select(URI.create("http://www.google.com"));
if (!proxyList.isEmpty())
Proxy proxy = proxyList.get(0);
switch (proxy.type())
case DIRECT:
System.out.println("Direct connection - no proxy.");
break;
case HTTP:
System.out.println("HTTP proxy: " + proxy.address());
break;
case SOCKS:
System.out.println("SOCKS proxy: " + proxy.address());
break;
【讨论】:
如何给选择器一个代理IP?是否可以避免系统范围的设置? 啊,我想我误解了你的问题。您想根据 IP 地址检测代理类型。我给出的解决方案是让 Java 查看系统配置。据我所知,Java 不会检测代理是什么类型,它只是从系统配置中读取它。要检测代理的类型,您可以尝试将其用作 HTTP 代理,然后使用 SOCKS 代理,然后选择不会失败的方法。以上是关于检查 Web 代理的类型的主要内容,如果未能解决你的问题,请参考以下文章