1 |
package dk.thoerup.traininfo.util; |
package dk.thoerup.traininfo.util; |
2 |
|
|
3 |
|
import java.io.ByteArrayOutputStream; |
4 |
|
import java.io.IOException; |
5 |
import java.io.InputStream; |
import java.io.InputStream; |
|
import java.io.InputStreamReader; |
|
6 |
import java.net.URL; |
import java.net.URL; |
7 |
import java.net.URLConnection; |
import java.net.URLConnection; |
|
import java.util.Date; |
|
8 |
|
|
9 |
public class DownloadUtil { |
public class DownloadUtil { |
10 |
|
|
11 |
public static String getContent(String uri, int timeout, String encoding) throws Exception { |
public static String getContentString(String uri, int timeout) throws IOException { |
12 |
char cbuffer[] = new char[256]; |
return getContentString(uri, timeout, "UTF-8"); |
13 |
StringBuffer buffer = new StringBuffer(128000); |
} |
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 |
|
|
|
Date start = new Date(); |
|
31 |
URL url = new URL(uri); |
URL url = new URL(uri); |
32 |
URLConnection connection = url.openConnection(); |
URLConnection connection = url.openConnection(); |
33 |
connection.setConnectTimeout(20000); |
connection.setConnectTimeout(connectTimeout); |
34 |
InputStream stream = connection.getInputStream(); |
InputStream is = connection.getInputStream(); |
35 |
|
|
36 |
InputStreamReader reader = new InputStreamReader(stream, encoding); |
try { |
37 |
int count; |
int count; |
38 |
while ( (count = reader.read(cbuffer)) != -1) { |
while ( (count = is.read(buffer)) != -1) { |
39 |
buffer.append(cbuffer, 0, count); |
baos.write(buffer, 0, count); |
40 |
|
|
41 |
Date now = new Date(); |
now = android.os.SystemClock.elapsedRealtime(); |
42 |
if ( (now.getTime()-start.getTime()) > timeout) |
|
43 |
throw new Exception("timeout"); |
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 |
return buffer.toString(); |
|
54 |
|
return baos.toByteArray(); |
55 |
} |
} |
56 |
|
|
57 |
} |
} |