2

如何使用 java 确定 Web 代理 IP 是 HTTP 类型还是 SOCKS4/5 类型?

谢谢你。

4

2 回答 2

2

正如我在另一个答案的评论中所提到的,如果您知道代理服务器的 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。

于 2011-07-26T23:21:06.510 回答
1

如果要确定 Java 使用的代理类型,可以使用ProxySelectorProxy

例如

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;
            }
        }
    }
}
于 2011-07-25T23:13:31.617 回答