package dk.thoerup.traininfo.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class DownloadUtil { public static String getContentString(String uri, int timeout) throws IOException { return getContentString(uri, timeout, "UTF-8"); } public static String getContentString(String uri, int timeout, String encoding) throws IOException { byte[] buf = getContent(uri, timeout); return new String(buf, encoding); } public static byte[] getContent(String uri, int timeout) throws IOException { byte buffer[] = new byte[256]; ByteArrayOutputStream baos = new ByteArrayOutputStream(32768); //start buffer size - instead of default 32bytes long start = android.os.SystemClock.elapsedRealtime(); //in j2se you would probably use java.lang.System.currentTimeMillis() long now = start; int connectTimeout = Math.min(timeout, 20000); // never use a connect Timeout larger than 20 seconds URL url = new URL(uri); URLConnection connection = url.openConnection(); connection.setConnectTimeout(connectTimeout); InputStream is = connection.getInputStream(); try { int count; while ( (count = is.read(buffer)) != -1) { baos.write(buffer, 0, count); now = android.os.SystemClock.elapsedRealtime(); if ( (now-start) > timeout) throw new IOException("timeout"); } } finally { try { is.close(); baos.close(); } catch (Exception e) {} //never mind if close throws an exception } return baos.toByteArray(); } }