Java URL Read getURL(String url)

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

Description

get URL

License

Apache License

Declaration

public static String getURL(String url) 

Method Source Code


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

import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String getURL(String url) {
        StringBuffer response = null;

        try {/*  w w  w  . ja  va 2 s  .c  o  m*/
            URL u = new URL(url);
            HttpURLConnection httpConnection = (HttpURLConnection) u.openConnection();

            httpConnection.setUseCaches(false);
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("GET");

            httpConnection.connect();
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream input = httpConnection.getInputStream();

                // Read server's response.
                response = new StringBuffer();
                Reader reader = new InputStreamReader(input, "UTF-8");
                reader = new BufferedReader(reader);
                char[] buffer = new char[1024];
                for (int n = 0; n >= 0;) {
                    n = reader.read(buffer, 0, buffer.length);
                    if (n > 0)
                        response.append(buffer, 0, n);
                }

                input.close();
                httpConnection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (response != null) {
            return response.toString();
        } else {
            return "";
        }
    }
}

Related

  1. getText(URL url)
  2. getTextFromURL(final String url)
  3. getTextFromURL(URL url)
  4. getTextFromURL(URL url)
  5. getURL(final URL url)
  6. getURL(URL url, String params)
  7. getUrlContent(String url)
  8. getURLContent_old(final String uri, final StringBuffer content)
  9. getUrlContentWithRetries(String url, long timeoutMs, long retryDelayMs)