Java URL Read readStringFromURL(String sourceURL)

Here you can find the source of readStringFromURL(String sourceURL)

Description

readStringFromURL - read the contents of a supplied URL into a string.

License

Apache License

Parameter

Parameter Description
sourceURL - the URL to read from.

Exception

Parameter Description
IOException an exception

Return

- the string read.

Declaration

public static String readStringFromURL(String sourceURL) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;

public class Main {
    /**//  w ww . j  av a  2 s. co m
     * readStringFromURL - read the contents of a supplied URL into a string.
     * 
     * @param sourceURL - the URL to read from.
     * @return          - the string read.
     * 
     * @throws IOException
     */
    public static String readStringFromURL(String sourceURL) throws IOException {
        StringBuilder content = new StringBuilder();

        // many of these calls can throw exceptions, so i've just
        // wrapped them all in one try/catch statement.
        try {
            // create a url object
            URL url = new URL(sourceURL);

            // create a urlconnection object
            URLConnection urlConnection = url.openConnection();

            // wrap the urlconnection in a bufferedreader
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            String line;

            // read from the urlconnection via the bufferedreader
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }

            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}

Related

  1. getUrlStatus(String url)
  2. getUrlTxt(String url)
  3. readAsString(final URL url)
  4. readListFromURL(URL p_url)
  5. readPage(String url)
  6. readUrl(final String strUrl)
  7. readUrl(final String url)
  8. readUrl(final String url_str)
  9. readURL(String path)