0

我有一个代理列表来测试它们是 HTTP 代理还是 Socks 代理,但是下面的 Java 代码在调用 connection.getContent() 或 connection.getInputStream() 时会挂起。我观察到当代理服务器无法响应并且代码阻塞等待服务器响应时会发生此问题,如何防止此代码在服务器无法响应时永远挂起/阻塞,以便检查下一个代理。

import java.io.*;
import java.net.*;
import java.util.*;

public class ProxyTest {

    public static void main(String[] args) throws IOException {

        InetSocketAddress proxyAddress = new InetSocketAddress("myproxyaddress", 1234);

        Proxy.Type proxyType = detectProxyType(proxyAddress);
    }

    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);

        URLConnection connection = null;

        try {

            connection = url.openConnection(proxy);

            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            connection.getContent();
            //connection.getInputStream();

            return(proxyType);
        }

        catch (SocketException e) {

    e.printStackTrace();
        }
    }

    return(null);
}
}
4

2 回答 2

1

要并行执行操作,请使用线程。

for(Foo f : foos){
    Thread t = new Thread(new Runnable(){
        @Override
        public void run(){
            // blocking call
        }        
    });
    t.start();
}

更好的是,利用java.util.concurrent包中的一种数据结构。

于 2012-07-20T19:56:34.977 回答
0

我相信对此没有简单的直接解决方案。答案取决于 JDK 版本、实现和运行环境。有关更多详细信息,请参阅Java URLConnection Timeout

于 2012-07-20T20:03:22.667 回答