1 |
torben |
238 |
package dk.thoerup.traininfo.util;
|
2 |
|
|
|
3 |
torben |
283 |
import java.io.ByteArrayOutputStream;
|
4 |
|
|
import java.io.IOException;
|
5 |
torben |
238 |
import java.io.InputStream;
|
6 |
|
|
import java.net.URL;
|
7 |
|
|
import java.net.URLConnection;
|
8 |
|
|
|
9 |
|
|
public class DownloadUtil {
|
10 |
|
|
|
11 |
torben |
283 |
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 |
torben |
238 |
|
21 |
torben |
283 |
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 |
torben |
238 |
URL url = new URL(uri);
|
32 |
|
|
URLConnection connection = url.openConnection();
|
33 |
torben |
283 |
connection.setConnectTimeout(connectTimeout);
|
34 |
|
|
InputStream is = connection.getInputStream();
|
35 |
torben |
238 |
|
36 |
torben |
283 |
try {
|
37 |
|
|
int count;
|
38 |
|
|
while ( (count = is.read(buffer)) != -1) {
|
39 |
|
|
baos.write(buffer, 0, count);
|
40 |
torben |
238 |
|
41 |
torben |
283 |
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 |
torben |
238 |
}
|
52 |
|
|
|
53 |
torben |
283 |
|
54 |
|
|
return baos.toByteArray();
|
55 |
torben |
238 |
}
|
56 |
|
|
|
57 |
|
|
}
|