Java HTTP GET Request with HttpURLConnection

In this example, we use the HttpURLConnection class to send an HTTP GET request to Google.com to get the search result.

HttpURLConnection Class - Java HTTP GET Request Example

package net.javaguides.network;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {

    private static final String USER_AGENT = "Mozilla/5.0";

    private static final String GET_URL = "https://www.google.com/search?q=javaguides";

    public static void main(String[] args) throws IOException {
        sendHttpGETRequest();
    }

    private static void sendHttpGETRequest() throws IOException {
        URL obj = new URL(GET_URL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = httpURLConnection.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in .readLine()) != null) {
                response.append(inputLine);
            } in .close();

            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("GET request not worked");
        }

        for (int i = 1; i <= 8; i++) {
            System.out.println(httpURLConnection.getHeaderFieldKey(i) + " = " + httpURLConnection.getHeaderField(i));
        }

    }
}
Output:
GET Response Code :: 200
Google search result ....
Date = Tue, 14 May 2019 08:50:16 GMT
Expires = -1
Cache-Control = private, max-age=0
Content-Type = text/html; charset=UTF-8
P3P = CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server = gws
X-XSS-Protection = 0
X-Frame-Options = SAMEORIGIN

Comments