Java HTTP Get doGet(String urlString)

Here you can find the source of doGet(String urlString)

Description

do Get

License

Open Source License

Declaration

public static String doGet(String urlString) 

Method Source Code


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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    private static int connectionTimeOut = 30 * 1000;
    private static int timeOut = 30 * 1000;

    public static String doGet(String urlString) {
        InputStream is = null;//w ww .j a va 2 s.  com
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setConnectTimeout(connectionTimeOut);
            conn.setReadTimeout(timeOut);

            StringBuffer buffer = new StringBuffer();
            String line = null;

            conn.connect();
            is = conn.getInputStream();
            //           inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(new InputStreamReader(is));

            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            tryClose(is);
            tryClose(reader);
            return buffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static void tryClose(InputStream is) {
        try {
            if (null != is) {
                is.close();
                is = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void tryClose(java.io.Reader reader) {
        try {
            if (null != reader) {
                reader.close();
                reader = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related

  1. doGET(HttpURLConnection conn)
  2. doGet(String theURL, Map nameValuePairs)
  3. doGet(String url)
  4. doGet(String url, HashMap params)
  5. doGet(String urlStr)
  6. doGet(URL url, String... args)
  7. doGetRequest(String urlStr)
  8. executeGet(String targetURL)
  9. getHttpURLConnectionByGET(String resourceURL)