Java HTTP Get doGet(String urlStr)

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

Description

do Get

License

Open Source License

Declaration

public static String doGet(String urlStr) 

Method Source Code

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

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

public class Main {
    private static final int TIMEOUT_IN_MILLIONS = 4000;

    public static String doGet(String urlStr) {
        URL url = null;/*w w w.j a  va2s . c  om*/
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];

                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                return baos.toString();
            } else {
                throw new RuntimeException(" responseCode is not 200 ... ");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
            }
            conn.disconnect();
        }

        return null;

    }
}

Related

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