Java HTTP GET/POST request

This tutorial shows how to send a GET and a POST request in Java. We use built-in HttpURLConnection class and Apache HttpClient class.

HTTP

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

In the examples, we use httpbin.org, which is a freely available HTTP request and response service.

HTTP GET

The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

HTTP POST

The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.

Java HTTP GET request with HttpURLConnection

The following example uses HttpURLConnection to create a GET request.

JavaGetRequest.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class JavaGetRequest {
    
    private static HttpURLConnection con;

    public static void main(String[] args) throws MalformedURLException,
            ProtocolException, IOException {

        String url = "http://www.something.com";

        try {

            URL myurl = new URL(url);
            con = (HttpURLConnection) myurl.openConnection();

            con.setRequestMethod("GET");

            StringBuilder content;

            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()))) {

                String line;
                content = new StringBuilder();

                while ((line = in.readLine()) != null) {
                    content.append(line);
                    content.append(System.lineSeparator());
                }
            }

            System.out.println(content.toString());

        } finally {
            
            con.disconnect();
        }
    }
}

The example retrieves a web page with HTTP GET request.

String url = "http://www.something.com";

We retrieve the contents of this tiny webpage.

URL myurl = new URL(url);
con = (HttpURLConnection) myurl.openConnection();

A connection to the specified URL is created.

con.setRequestMethod("GET");

We set the request method type with setRequestMethod() method.

try (BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream()))) {

An input stream is created from the HTTP connection object. The input stream is used to read the returned data.

content = new StringBuilder();

We use StringBuilder to build the content string.

while ((line = in.readLine()) != null) {
    content.append(line);
    content.append(System.lineSeparator());
}

We read the data from the input stream line by line with readLine(). Each line is added to StringBuilder. After a line we append a system-dependent line separator string;

Java HTTP POST request with HttpURLConnection

The following example uses HttpURLConnection to create a POST request.

JavaPostRequest.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class JavaPostRequest {

    private static HttpURLConnection con;

    public static void main(String[] args) throws MalformedURLException,
            ProtocolException, IOException {

        String url = "https://httpbin.org/post";
        String urlParameters = "name=Jack&occupation=programmer";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

        try {

            URL myurl = new URL(url);
            con = (HttpURLConnection) myurl.openConnection();

            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Java client");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
                wr.write(postData);
            }

            StringBuilder content;

            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()))) {

                String line;
                content = new StringBuilder();

                while ((line = in.readLine()) != null) {
                    content.append(line);
                    content.append(System.lineSeparator());
                }
            }

            System.out.println(content.toString());

        } finally {
            
            con.disconnect();
        }
    }
}

The example sends a POST request to https://httpbin.org/post.

String urlParameters = "name=Jack&occupation=programmer";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

We are going to write these two key/value pairs. We transform the strings into an array of bytes.

URL myurl = new URL(url);
con = (HttpURLConnection) myurl.openConnection();

A connection to the URL is opened.

con.setDoOutput(true);

With setDoOutput() method we indicate that we are going to write data to the URL connection.

con.setRequestMethod("POST");

The HTTP request type is set with setRequestMethod().

con.setRequestProperty("User-Agent", "Java client");

We set the user age property with setRequestProperty() method.

try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
    wr.write(postData);
}

We write the bytes or our data to the URL connection.

Java HTTP GET request with Apache HttpClient

The following example uses Apache HttpClient to create a GET request.

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.4</version>
</dependency>

For the examples, we need this Maven dependency.

ApacheHttpClientGet.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class ApacheHttpClientGet {

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

        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        
            HttpGet request = new HttpGet("http://www.something.com");
            HttpResponse response = client.execute(request);

            BufferedReader bufReader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            StringBuilder builder = new StringBuilder();

            String line;

            while ((line = bufReader.readLine()) != null) {
                builder.append(line);
                builder.append(System.lineSeparator());
            }

            System.out.println(builder);
        }
    }
}

The example sends a GET request to read the home page of the specified webpage.

try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

CloseableHttpClient is built with HttpClientBuilder.

HttpGet request = new HttpGet("http://www.something.com");

HttpGet is used to create an HTTP GET request.

HttpResponse response = client.execute(request);

We execute the request and get a response.

BufferedReader bufReader = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent()));

From the response object, we read the content.

while ((line = bufReader.readLine()) != null) {
    builder.append(line);
    builder.append(System.lineSeparator());
}

We read the content line by line and dynamically build a string message.

Java HTTP POST with HttpClient

The following example uses HttpPost to create a POST request.

ApacheHttpClientPost.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class ApacheHttpClientPost {

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

        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

            HttpPost request = new HttpPost("https://httpbin.org/post");
            request.setHeader("User-Agent", "Java client");
            request.setEntity(new StringEntity("My test data"));

            HttpResponse response = client.execute(request);

            BufferedReader bufReader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            StringBuilder builder = new StringBuilder();

            String line;

            while ((line = bufReader.readLine()) != null) {
                builder.append(line);
                builder.append(System.lineSeparator());
            }

            System.out.println(builder);
        }
    }
}

The example sends a POST request to https://httpbin.org/post.

HttpPost request = new HttpPost("https://httpbin.org/post");

HttpPost is used to create a POST request.

request.setEntity(new StringEntity("My test data"));

The data is sent with setEntity() method.

request.setHeader("User-Agent", "Java client");

We set a header to the request; the header is read in the servlet.

In this tutorial, we have created a GET and a POST request in Java with HttpURLConnection and HttpClient.

You might also be interested in the following related tutorials: Python Requests tutorial, Jsoup tutorial, Java tutorial, Reading a web page in Java, or Introduction to Google Guava.