1 |
package dk.thoerup.traininfoservice;
|
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 = 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 = System.currentTimeMillis();
|
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 |
} |