0

I have a list of proxies to test if they are HTTP or Socks proxies, but the Java code below hangs when it calls the connection.getContent() or connection.getInputStream(). I observed that this issue occur when the proxy server fail to respond and the code blocks waiting for response from server, How can I prevent this code from hanging/blocking forever when the server fail to respond, so that the next proxy can be checked.

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);
}
}
John
  • 1,699
  • 5
  • 20
  • 29

2 Answers2

1

To do things in parallel, use threads.

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

Better yet, make use of one of the data structures in the java.util.concurrent package.

user1329572
  • 6,176
  • 5
  • 29
  • 39
  • I tried this but the thread t will never stop/finish it will hang when connection.getContent() is called. – John Jul 20 '12 at 20:03
  • +1 for threads suggestion. This is the way to make nonblockign (atleast on the main thread) requests. @john You could always call Thread.interupt() at some interval and have that thread check whether it should stop itself. – hsanders Jul 20 '12 at 20:21
0

I believe there is no and simple straight solution for this. The answer depends on JDK version, implementation and runtime environment. For more details please see Java URLConnection Timeout.

Community
  • 1
  • 1
Dmitry B.
  • 9,107
  • 3
  • 43
  • 64