Here you can find the source of readURL(String url, String type)
Parameter | Description |
---|---|
url | the URL to read |
type | the accepted content type |
public static String readURL(String url, String type)
//package com.java2s; //License from project: Open Source License import java.io.*; import java.net.*; public class Main { /**/*ww w. j a v a 2 s . com*/ * Read the contents of the specified URL and store it in a string. * @param url the URL to read * @param type the accepted content type * @return a string containing the URL contents */ public static String readURL(String url, String type) { HttpURLConnection.setFollowRedirects(false); HttpURLConnection conn = null; BufferedReader ins; StringBuilder outs = new StringBuilder(); char[] buffer = new char[1024]; //String line; String contents = ""; int tmpi; try { conn = (HttpURLConnection) new URL(url).openConnection(); if (type != null) conn.setRequestProperty("Accept", type); conn.connect(); ins = new BufferedReader(new InputStreamReader( conn.getInputStream())); /* while((line = ins.readLine()) != null){ contents += line + "\n"; } */ do { tmpi = ins.read(buffer, 0, buffer.length); if (tmpi > 0) outs.append(buffer, 0, tmpi); } while (tmpi >= 0); contents = outs.toString(); conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } return contents; } /** * Read the contents of the specified URL and store it in a string. * @param url the URL to read * @return a string containing the URL contents */ public static String readURL(String url) { return readURL(url, null); } }