Java URL Load readFromUrl(String url)

Here you can find the source of readFromUrl(String url)

Description

Reads a url and returns the content as a string.

License

Open Source License

Parameter

Parameter Description
url url to read from

Exception

Parameter Description
IOException The uri cannot be read.

Return

url contents as a string

Declaration

public static String readFromUrl(String url) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012, 2016 Apcera Inc./*w  ww  .j  a v a 2  s  .co  m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the MIT License (MIT)
 * which accompanies this distribution, and is available at
 * http://opensource.org/licenses/MIT
 *******************************************************************************/

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

public class Main {
    /**
     * Reads a url and returns the content as a string.  Useful for reading a
     * configuration in a cloud environment.
     *
     * @param url url to read from
     * @return url contents as a string
     * @throws IOException The uri cannot be read.
     */
    public static String readFromUrl(String url) throws IOException {
        InputStream is = new URL(url).openStream();

        StringBuilder sb = null;

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"));

            String line;
            while ((line = br.readLine()) != null) {
                if (sb == null)
                    sb = new StringBuilder();

                sb.append(line);
            }

            return sb.toString();

        } finally {
            is.close();
        }
    }
}

Related

  1. readFileIntoMap(URL url)
  2. readFileIntoString(URL input)
  3. readFileIntoString(URL url)
  4. readFromFile(URL fileName)
  5. readFromFile(URL source)
  6. readFromUrl(String urlString)
  7. readFromUrl(String urlText)
  8. readFromUrl(URL url)
  9. readFromURL(URL url)