Java URL Load readUrlText(final URL url, final String encoding)

Here you can find the source of readUrlText(final URL url, final String encoding)

Description

reads the content from the given URL using the given character encoding.

License

Apache License

Parameter

Parameter Description
url URL
encoding encoding, e.g. "UTF-8"

Exception

Parameter Description
IOException if could not read from the URL

Declaration

public static String readUrlText(final URL url, final String encoding) throws IOException 

Method Source Code

//package com.java2s;
/*/*w  w w .j  a  va2  s  .  c  o  m*/
   Copyright 2014-now by Alain Stalder. Made in Switzerland.
    
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
    
   http://www.apache.org/licenses/LICENSE-2.0
    
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

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

import java.util.Scanner;

public class Main {
    /**
     * reads the content from the given URL using the given character encoding.
     * 
     * @param url URL
     * @param encoding encoding, e.g. "UTF-8"
     * @throws IOException if could not read from the URL
     * 
     * @since 1.0
     */
    public static String readUrlText(final URL url, final String encoding) throws IOException {
        InputStream in;
        try {
            in = url.openStream();
        } catch (IOException e) {
            throw new IOException("Could not open stream for URL '" + url + "': " + e, e);
        }

        Scanner scanner = new Scanner(in, encoding);
        scanner.useDelimiter("\\A");
        String text = scanner.hasNext() ? scanner.next() : "";
        scanner.close();
        IOException e = scanner.ioException();
        if (e != null) {
            throw new IOException("Could not read from URL '" + url + "': " + e, e);
        }

        return text;
    }
}

Related

  1. readUrlContent(String address)
  2. readURLContents(String UrlText)
  3. readURLJSONArray(String urlString)
  4. readUrlProperties(URL url)
  5. readUrlStream(String urlString)
  6. readURLText(String urlPath, String encoding)
  7. readUrlText(String urlString)
  8. readURLText(URL url, StringBuffer errorText)
  9. readURLThrowException(final String url)