Java HttpUrlConnection GET request example

Let’s consider Java example how to call the HTTP GET method using standard java.net API.


HttpUrlConnection GET method

So, let’s image, we need to get response from the HTTP GET method. To do it, we need an URL and simple Java code:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

InputStream in = null;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
    in = connection.getInputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = in.read(buffer)) != -1) {
        bout.write(buffer, 0, length);
    }
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (IOException ignored) {
        }
    }
}

String responseBody = bout.toString("UTF-8");

Full Java code example

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Denis Migol
 */
public class HttpUrlConnectionGetRequestExample {
    public static void main(String[] args) throws IOException {
        String url = "http://httpbin.org/get";

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

        InputStream in = null;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        try {
            in = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) != -1) {
                bout.write(buffer, 0, length);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }

        String responseBody = bout.toString("UTF-8");
        System.out.println(responseBody);
    }
}

Output

{
  "args": {}, 
  "headers": {
    "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", 
    "Host": "httpbin.org", 
    "User-Agent": "Java/1.8.0_25"
  }, 
  "origin": "12.123.222.22, 12.123.222.22", 
  "url": "https://httpbin.org/get"
}