1 | public static String loadPage(URL url) throws IOException { |
2 | System.out.println("Loading: " + url.toExternalForm()); |
3 | URLConnection con = url.openConnection(); |
4 | return loadPage(con, url); |
5 | } |
6 | |
7 | public static String loadPage(URLConnection con, URL url) throws IOException { |
8 | String contentType = con.getContentType(); |
9 | if (contentType == null) |
10 | throw new IOException("Page could not be read: " + url); |
11 | //Log.info("Content-Type: " + contentType); |
12 | String charset = loadPage_guessCharset(contentType); |
13 | Reader r = new InputStreamReader(con.getInputStream(), charset); |
14 | StringBuilder buf = new StringBuilder(); |
15 | while (true) { |
16 | int ch = r.read(); |
17 | if (ch < 0) |
18 | break; |
19 | //Log.info("Chars read: " + buf.length()); |
20 | buf.append((char) ch); |
21 | } |
22 | return buf.toString(); |
23 | } |
24 | |
25 | static String loadPage_guessCharset(String contentType) { |
26 | Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); |
27 | Matcher m = p.matcher(contentType); |
28 | /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ |
29 | return m.matches() ? m.group(1) : "ISO-8859-1"; |
30 | } |
31 | } |
supersedes #2000480
Snippet is not live.
Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
No comments. add comment
Snippet ID: | #2000481 |
Snippet name: | loadPage |
Eternal ID of this version: | #2000481/1 |
Text MD5: | 22c8b5ccb3621ffc99811b01e8b37823 |
Author: | stefan |
Category: | |
Type: | New Tinybrain snippet |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-08-02 14:50:52 |
Source code size: | 1196 bytes / 31 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 528 / 155 |
Referenced in: | [show references] |