Report this

What is the reason for this report?

How To Use Java HttpURLConnection for HTTP GET and POST Requests

Updated on November 19, 2022
How To Use Java HttpURLConnection for HTTP GET and POST Requests

Introduction

The HttpURLConnection class from java.net package can be used to send a Java HTTP Request programmatically. In this article, you will learn how to use HttpURLConnection in a Java program to send GET and POST requests and then print the response.

Prerequisites

For this HttpURLConnection example, you should have completed the Spring MVC Tutorial because it has URLs for GET and POST HTTP methods.

Consider deploying to a localhost Tomcat server.

SpringMVCExample Summary

Java HTTP GET Request

  • localhost:8080/SpringMVCExample/

Spring-MVC-HelloWorld

Java HTTP GET Request for Login Page

  • localhost:8080/SpringMVCExample/login

Spring-MVC-HelloWorld-GET

Java HTTP POST Request

  • localhost:8080/SpringMVCExample?userName=Pankaj
  • localhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123 - for multiple params

Spring-MVC-HelloWorld-POST

Deriving parameters from the form

The HTML of the login page contains the following form:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="home" method="post">
<input type="text" name="userName"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
  • The method is POST.
  • The action is home.
    • localhost:8080/SpringMVCExample/home
  • userName is of type text.

You can construct a POST request to:

localhost:8080/SpringMVCExample/home?userName=Pankaj

This will serve as the basis for the HttpURLConnection example.

HttpURLConnection Example

Here are the steps for sending Java HTTP requests using HttpURLConnection class:

  1. Create a URL object from the GET or POST URL String.
  2. Call the openConnection() method on the URL object that returns an instance of HttpURLConnection.
  3. Set the request method in HttpURLConnection instance (default value is GET).
  4. Call setRequestProperty() method on HttpURLConnection instance to set request header values (such as "User-Agent", "Accept-Language", etc).
  5. We can call getResponseCode() to get the response HTTP code. This way, we know if the request was processed successfully or if there was any HTTP error message thrown.
  6. For GET, use Reader and InputStream to read the response and process it accordingly.
  7. For POST, before the code handles the response, it needs to get the OutputStream from the HttpURLConnection instance and write POST parameters into it.

Here is an example program that uses HttpURLConnection to send Java GET and POST requests:

HttpURLConnectionExample.java
package com.journaldev.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
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://localhost:9090/SpringMVCExample";

	private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";

	private static final String POST_PARAMS = "userName=Pankaj";

	public static void main(String[] args) throws IOException {
		sendGET();
		System.out.println("GET DONE");
		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendGET() throws IOException {
		URL obj = new URL(GET_URL);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("User-Agent", USER_AGENT);
		int responseCode = con.getResponseCode();
		System.out.println("GET Response Code :: " + responseCode);
		if (responseCode == HttpURLConnection.HTTP_OK) { // success
			BufferedReader in = new BufferedReader(new InputStreamReader(con.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 did not work.");
		}

	}

	private static void sendPOST() throws IOException {
		URL obj = new URL(POST_URL);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);

		// For POST only - START
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(POST_PARAMS.getBytes());
		os.flush();
		os.close();
		// For POST only - END

		int responseCode = con.getResponseCode();
		System.out.println("POST Response Code :: " + responseCode);

		if (responseCode == HttpURLConnection.HTTP_OK) { //success
			BufferedReader in = new BufferedReader(new InputStreamReader(con.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("POST request did not work.");
		}
	}

}

Compile and run the code. It will produce the following output:

Output
GET Response Code :: 200 <html><head> <title>Home</title></head><body><h1> Hello world! </h1><P> The time on the server is March 6, 2015 9:31:04 PM IST. </P></body></html> GET DONE POST Response Code :: 200 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj</h3></body></html> POST DONE

Compare this output to the browser HTTP response.

If you have to send GET and POST requests over HTTPS protocol, then you need to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. HttpsURLConnection will handle the SSL handshake and encryption.

Conclusion

In this article, you learned how to use HttpURLConnection in a Java program to send GET and POST requests and then print the response.

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Category:
Tags:

Still looking for an answer?

Was this helpful?

Hi, I wast tried to hit an end point which is get to fetch the detail using apache http, the json response that I get has got some attributes which are empty array. But the same end point I hit thru a browser or a rest client I don’t see these attributes as part of json response. Why is that ?

- abhineet

Thanks man! This really worked as expected. Good job (y)

- Gurgen

Nice tutorial. Well I didn’t get on thing. `os.write(POST_PARAMS.getBytes()); os.flush(); os.close();` How can I print my complete POST URL, after adding parameters. Is that possible to output the URL?

- akshay

This tutorial is great and clear. But how about 2 parameters?

- mbrean

Thanks :D

- Rinaldes Duma

hello am getting error : javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake. I did same as above except for https connection. please help.

- KIRAN

Many thanks - I’ve been puzzling over how to POST from a Spring Controller and your article was a great help. Andrew (Sheffield UK)

- Andrew

is there any way to get request url from browser console

- suman

I have to say I’m new to Java but have worked with C, C++ , python and several other languages. Java was the hardest for me to understand and work with but this little tutorial made it very plain how to use the java.net module the way I wanted. Very Nice Job!

- Mathew Eickmeyer

Really awesome tutorials so easy to understand. Thanks pankaj.

- Nidh

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.