Java URL Read readAsString(final URL url)

Here you can find the source of readAsString(final URL url)

Description

read As String

License

Open Source License

Declaration

public static String readAsString(final URL url) throws IOException 

Method Source Code


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

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

public class Main {
    public static String readAsString(final URL url) throws IOException {
        final URLConnection conn = url.openConnection();
        //ohne den User-Agent zu setzen kommt meistens ein 403
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        final StringWriter buffer = new StringWriter();
        try (InputStream in = conn.getInputStream()) {
            final InputStreamReader r = new InputStreamReader(in,
                    conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding());
            int ch;
            while ((ch = r.read()) >= 0) {
                buffer.write(ch);/*from w  w  w .j av a  2s  . c  om*/
            }
        }
        return buffer.toString();
    }
}

Related

  1. getUrlFollowingRedirects(String possibleRedirectionUrl)
  2. getUrlInfos(String urlAsString, int timeout)
  3. getUrlSource(String url)
  4. getUrlStatus(String url)
  5. getUrlTxt(String url)
  6. readListFromURL(URL p_url)
  7. readPage(String url)
  8. readStringFromURL(String sourceURL)
  9. readUrl(final String strUrl)