/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/util/DownloadUtil.java
ViewVC logotype

Contents of /android/TrainInfo/src/dk/thoerup/traininfo/util/DownloadUtil.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 283 - (show annotations) (download)
Thu Aug 27 08:34:50 2009 UTC (14 years, 8 months ago) by torben
File size: 1677 byte(s)
Make downloadUtil a little more intelligent

1 package dk.thoerup.traininfo.util;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.net.URL;
7 import java.net.URLConnection;
8
9 public class DownloadUtil {
10
11 public static String getContentString(String uri, int timeout) throws IOException {
12 return getContentString(uri, timeout, "UTF-8");
13 }
14
15 public static String getContentString(String uri, int timeout, String encoding) throws IOException {
16 byte[] buf = getContent(uri, timeout);
17 return new String(buf, encoding);
18 }
19
20
21 public static byte[] getContent(String uri, int timeout) throws IOException {
22 byte buffer[] = new byte[256];
23
24 ByteArrayOutputStream baos = new ByteArrayOutputStream(32768); //start buffer size - instead of default 32bytes
25
26 long start = android.os.SystemClock.elapsedRealtime(); //in j2se you would probably use java.lang.System.currentTimeMillis()
27 long now = start;
28
29 int connectTimeout = Math.min(timeout, 20000); // never use a connect Timeout larger than 20 seconds
30
31 URL url = new URL(uri);
32 URLConnection connection = url.openConnection();
33 connection.setConnectTimeout(connectTimeout);
34 InputStream is = connection.getInputStream();
35
36 try {
37 int count;
38 while ( (count = is.read(buffer)) != -1) {
39 baos.write(buffer, 0, count);
40
41 now = android.os.SystemClock.elapsedRealtime();
42
43 if ( (now-start) > timeout)
44 throw new IOException("timeout");
45 }
46 } finally {
47 try {
48 is.close();
49 baos.close();
50 } catch (Exception e) {} //never mind if close throws an exception
51 }
52
53
54 return baos.toByteArray();
55 }
56
57 }

  ViewVC Help
Powered by ViewVC 1.1.20