Table of Contents
URL: https://www.progressiverobot.com/java-httpurlconnection-example-java-http-request-get-post/
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](/community/tutorials/spring-mvc-tutorial) because it has URLs for GET and POST HTTP methods.
Consider deploying to a localhost Tomcat server.
Java HTTP GET Request
localhost:8080/SpringMVCExample/

Java HTTP GET Request for Login Page
localhost:8080/SpringMVCExample/login

Java HTTP POST Request
localhost:8080/SpringMVCExample?userName=Pankajlocalhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123– for multiple params

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
methodisPOST. - The
actionishome. localhost:8080/SpringMVCExample/homeuserNameis of typetext.
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:
- Create a
URLobject from theGETorPOSTURL String. - Call the
openConnection()method on the URL object that returns an instance ofHttpURLConnection. - Set the request method in
HttpURLConnectioninstance (default value isGET). - Call
setRequestProperty()method onHttpURLConnectioninstance to set request header values (such as"User-Agent","Accept-Language", etc). - 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. - For
GET, useReaderandInputStreamto read the response and process it accordingly. - For
POST, before the code handles the response, it needs to get theOutputStreamfrom theHttpURLConnectioninstance and writePOSTparameters into it.
Here is an example program that uses HttpURLConnection to send Java GET and POST requests:
[label 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:
[secondary_label 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.