Java URL Connection urlToString(String url)

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

Description

url To String

License

Apache License

Declaration

public static String urlToString(String url) throws IOException 

Method Source Code

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

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

public class Main {
    public static final String CHARSET_UTF8 = "UTF-8";
    private static final String CHARSET_MARKER = "charset=";

    public static String urlToString(String url) throws IOException {
        URLConnection conn = new URL(url).openConnection();
        InputStream is = conn.getInputStream();
        String contentType = conn.getContentType();
        if (contentType != null) {
            contentType = contentType.toLowerCase();
            int i = contentType.indexOf(CHARSET_MARKER);
            if (i > -1) {
                String charsetName = contentType.substring(i + CHARSET_MARKER.length());
                return toString(is, charsetName);
            }/*ww w. j a  v a  2  s  .com*/
        }
        return toString(is, CHARSET_UTF8);
    }

    public static String toString(InputStream input, String charset) throws IOException {
        if (charset != null) {
            try (InputStreamReader reader = new InputStreamReader(input, charset)) {
                StringBuilder sb = new StringBuilder(1024 * 32);
                char[] buf = new char[1024];
                int n;
                while ((n = reader.read(buf)) != -1) {
                    sb.append(buf, 0, n);
                }
                return sb.toString();
            }
        } else {
            try (InputStreamReader reader = new InputStreamReader(input)) {
                StringBuilder sb = new StringBuilder(1024 * 32);
                char[] buf = new char[1024];
                int n;
                while ((n = reader.read(buf)) != -1) {
                    sb.append(buf, 0, n);
                }
                return sb.toString();
            }
        }
    }
}

Related

  1. urlExists(String urlString)
  2. URLExists(URL url, StringBuffer errorMsg)
  3. urlifyMap(Long nid, double latitude, double longitude)
  4. urlToHtm(String word, String findurl, String path)
  5. urlToReader(URL url)
  6. urlToText(@Nonnull String url)