--- android/TrainInfo/src/dk/thoerup/traininfo/util/DownloadUtil.java 2009/08/26 12:42:01 282 +++ android/TrainInfo/src/dk/thoerup/traininfo/util/DownloadUtil.java 2009/08/27 08:34:50 283 @@ -1,34 +1,57 @@ package dk.thoerup.traininfo.util; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; -import java.util.Date; public class DownloadUtil { - public static String getContent(String uri, int timeout, String encoding) throws Exception { - char cbuffer[] = new char[256]; - StringBuffer buffer = new StringBuffer(128000); + 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 - Date start = new Date(); URL url = new URL(uri); URLConnection connection = url.openConnection(); - connection.setConnectTimeout(20000); - InputStream stream = connection.getInputStream(); + connection.setConnectTimeout(connectTimeout); + InputStream is = connection.getInputStream(); - InputStreamReader reader = new InputStreamReader(stream, encoding); - int count; - while ( (count = reader.read(cbuffer)) != -1) { - buffer.append(cbuffer, 0, count); + try { + int count; + while ( (count = is.read(buffer)) != -1) { + baos.write(buffer, 0, count); - Date now = new Date(); - if ( (now.getTime()-start.getTime()) > timeout) - throw new Exception("timeout"); + 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 buffer.toString(); + + return baos.toByteArray(); } }