By Pankaj Kumar and Bradley Kouchi
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.
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.
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=Pankaj
localhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123
- for multiple paramsThe 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>
method
is POST
.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
ExampleHere are the steps for sending Java HTTP requests using HttpURLConnection
class:
URL
object from the GET
or POST
URL String.openConnection()
method on the URL object that returns an instance of HttpURLConnection
.HttpURLConnection
instance (default value is GET
).setRequestProperty()
method on HttpURLConnection
instance to set request header values (such as "User-Agent"
, "Accept-Language"
, etc).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.GET
, use Reader
and InputStream
to read the response and process it accordingly.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:
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:
OutputGET 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.
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.
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
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
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
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
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.