Programming Tips - Java: download a webpage

Date: 2022dec6 Language: Java Platform: non-Andr*id Keywods: web, page, http Q. Java: download a webpage A.
// Plain Java (non-Andr*id) void getUrlDirect(final String strUrl) throws IOException, MalformedURLException, CertificateException { HttpURLConnection uc = null; try { URL url = new URL(strUrl); uc = (HttpURLConnection)url.openConnection(); uc.connect(); String strResponseCode = uc.getResponseCode(); String strResponseMessage = uc.getResponseMessage(); String strContentType = uc.getContentType(); if (response.mResponseRange == HttpURLConnection.HTTP_OK) { String strContent = readContent(uc); } else { String strContent = readError(uc); } } finally { if (uc != null) { uc.disconnect(); } } } // Helpers static String readStream(InputStream is) throws IOException { if (is == null) return ""; BufferedReader br = null; try { StringBuilder sb = new StringBuilder(); br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n"); } return sb.toString(); } finally { if (br != null) { br.close(); } } } static String readContent(HttpURLConnection uc) throws IOException { return readStream(uc.getInputStream()); } static String readError(HttpURLConnection uc) throws IOException { return readStream(uc.getErrorStream()); }