Java HTTP Get readURL(String url, String type)

Here you can find the source of readURL(String url, String type)

Description

Read the contents of the specified URL and store it in a string.

License

Open Source License

Parameter

Parameter Description
url the URL to read
type the accepted content type

Return

a string containing the URL contents

Declaration

public static String readURL(String url, String type) 

Method Source Code

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

import java.io.*;
import java.net.*;

public class Main {
    /**/*ww  w.  j  a v  a 2  s . com*/
     * Read the contents of the specified URL and store it in a string.
     * @param url the URL to read
     * @param type the accepted content type
     * @return a string containing the URL contents
     */
    public static String readURL(String url, String type) {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection conn = null;
        BufferedReader ins;
        StringBuilder outs = new StringBuilder();
        char[] buffer = new char[1024];
        //String line;
        String contents = "";
        int tmpi;

        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            if (type != null)
                conn.setRequestProperty("Accept", type);
            conn.connect();

            ins = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));

            /*
            while((line = ins.readLine()) != null){
              contents += line + "\n";
            }
             */

            do {
                tmpi = ins.read(buffer, 0, buffer.length);
                if (tmpi > 0)
                    outs.append(buffer, 0, tmpi);
            } while (tmpi >= 0);

            contents = outs.toString();

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                conn.disconnect();
        }

        return contents;
    }

    /**
     * Read the contents of the specified URL and store it in a string.
     * @param url the URL to read
     * @return a string containing the URL contents
     */
    public static String readURL(String url) {
        return readURL(url, null);
    }
}

Related

  1. httpGetString(String url)
  2. readUrl(final String strUrl)
  3. readURL(final String textURL)
  4. readUrl(HttpURLConnection conn)
  5. readUrl(String url, String token)
  6. readUrl(String urlAsString, int timeout)
  7. readURL(URL url)
  8. requestGetMethod(String url, String... params)