1 24 25 package com.jdon.util; 26 27 import java.net.*; 28 import java.io.*; 29 30 public class URLUtil { 31 32 private URLConnection connection = null; 33 private URL url = null; 34 private boolean timedOut = false; 35 36 protected URLUtil() {} 37 38 protected URLUtil(URL url) { 39 this.url = url; 40 } 41 42 protected synchronized URLConnection openConnection(int timeout) throws 43 IOException { 44 Thread t = new Thread (new URLConnectorThread()); 45 t.start(); 46 47 try { 48 this.wait(timeout); 49 } catch (InterruptedException e) { 50 if (connection == null) 51 timedOut = true; 52 else 53 close(connection); 54 throw new IOException("Connection never established"); 55 } 56 57 if (connection != null) { 58 return connection; 59 } else { 60 timedOut = true; 61 throw new IOException("Connection timed out"); 62 } 63 } 64 65 public static URLConnection openConnection(URL url) throws IOException { 66 return openConnection(url, 30000); 67 } 68 69 public static URLConnection openConnection(URL url, int timeout) throws 70 IOException { 71 URLUtil uc = new URLUtil(url); 72 return uc.openConnection(timeout); 73 } 74 75 private class URLConnectorThread implements Runnable { 77 public void run() { 78 URLConnection con = null; 79 try { 80 con = url.openConnection(); 81 } catch (IOException e) {} 82 83 synchronized (URLUtil.this) { 84 if (timedOut && con != null) 85 close(con); 86 else { 87 connection = con; 88 URLUtil.this.notify(); 89 } 90 } 91 } 92 } 93 94 private static void close(URLConnection con) { 96 if (con instanceof HttpURLConnection) { 97 ( (HttpURLConnection) con).disconnect(); 98 } 99 } 100 101 102 } 103 | Popular Tags |