Java URLConnection Timeout
Try this:
import java.net.HttpURLConnection; URL url = new URL("http://www.myurl.com/sample.xml"); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(false); huc.setConnectTimeout(15 * 1000); huc.setRequestMethod("GET"); huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); huc.connect(); InputStream input = huc.getInputStream();
OR
import org.jsoup.nodes.Document; Document doc = null; try { doc = Jsoup.connect("http://www.myurl.com/sample.xml").get(); } catch (Exception e) { //log error }
And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url
You can manually force disconnection by a Thread sleep. This is an example:
URLConnection con = url.openConnection();con.setConnectTimeout(5000);con.setReadTimeout(5000);new Thread(new InterruptThread(con)).start();
then
public class InterruptThread implements Runnable { HttpURLConnection con; public InterruptThread(HttpURLConnection con) { this.con = con; } public void run() { try { Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout()) } catch (InterruptedException e) { } con.disconnect(); System.out.println("Timer thread forcing to quit connection"); }}
You can set timeouts for all connections made from the jvm by changing the following System-properties:
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");System.setProperty("sun.net.client.defaultReadTimeout", "10000");
Every connection will time out after 10 seconds.
Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.