How to send HTTP GET POST request in Java

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.

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.

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 {

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

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

        URL myurl = new URL(url);
        HttpURLConnection 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);
            }
        }
        
        System.out.println(content.toString());
    }
}

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);
HttpURLConnection 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);
}

We read the data from the input stream line by line with readLine(). Each line is added to StringBuilder.

HTTP POST request with HttpURLConnection

The following example uses HttpURLConnection to create a POST request.

ApacheHttpClientPost.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 JavaPostRequest {

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

        String url = "http://localhost:8084/MyServlet";

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

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

        StringBuilder content;
        
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {
            
            String line;
            content = new StringBuilder();
            
            while ((line = in.readLine()) != null) {
                content.append(line);
            }
        }
        
        System.out.println(content.toString());
    }
}

The example sends a POST request to a Java servlet.

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.

MyServlet.java
package com.zetcode.web;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/plain;charset=UTF-8");

        String agent = request.getHeader("User-Agent");
        
        String message = String.format("POST request from %s", agent);
        
        PrintWriter out = response.getWriter();
        
        out.println(message);
    }
}

This Java servlet processes a POST request. It reads the user agent header and builds a string message, which is sent back to the client.

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.3</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.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class ApacheHttpClientGet {

    public static void main(String[] args) throws IOException {
        
        HttpClient 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);
        }
        
        System.out.println(builder);
    }
}

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

HttpClient client = HttpClientBuilder.create().build();

HttpClient is built with HttpClientBuilder.

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

HttpGet is used to create a 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);
}

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

HTTP POST with HttpURLConnection

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.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;

public class ApacheHttpClientPost {
    
        public static void main(String[] args) throws IOException {
        
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost("http://localhost:8084/MyServlet");
        request.setHeader("User-Agent", "Java client");
        
        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);
        }
        
        System.out.println(builder);
    }
}

The example sends a POST request to a Java servlet.

HttpPost request = new HttpPost("http://localhost:8084/MyServlet");

HttpPost is used to create a POST request.

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.