Java URL Read readUrl(URL url)

Here you can find the source of readUrl(URL url)

Description

Read the contents of a URL as text

License

Open Source License

Parameter

Parameter Description
url Url to read

Exception

Parameter Description
IOException If an error occurs while reading the connexion

Return

Contents of the URL

Declaration

public static String readUrl(URL url) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    /**/*w  ww .ja v  a 2 s .  c om*/
     * Read the contents of a URL as text
     * @param url Url to read
     * @return Contents of the URL
     * @throws IOException If an error occurs while reading the connexion
     */
    public static String readUrl(URL url) throws IOException {
        StringBuilder sb = new StringBuilder();
        //ByteArrayOutputStream baos = new ByteArrayOutputStream();

        URLConnection con = url.openConnection();
        con.setConnectTimeout(1000);
        con.setReadTimeout(2000);
        InputStream in = con.getInputStream();

        String enc = con.getHeaderField("Content-Type");
        enc = enc.substring(enc.indexOf("charset=") > 0 ? enc.indexOf("charset=") + 8 : enc.length());
        if (enc.length() < 3)
            enc = "UTF-8";

        BufferedReader br = new BufferedReader(new InputStreamReader(in, enc));

        String line;
        while ((line = br.readLine()) != null)
            sb.append(line).append('\n');

        br.close();

        return sb.toString();
    }
}

Related

  1. readUrl(final String url)
  2. readUrl(final String url_str)
  3. readURL(String path)
  4. readUrl(String url_str)
  5. readUrl(String urlString)
  6. readURL(URL url)
  7. readUrl(URL url, String[]... headers)
  8. readURL(URLConnection connection, String charset)
  9. readUrlContent(URLConnection connection)