🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
HttpURLConnection class from java.net package can be used to send Java HTTP Request programmatically. In this post, we will learn how to use HttpURLConnection in java program to send GET and POST requests and then print the response.
HttpURLConnection Class - Java HTTP GET Request Example
In this example, we use HttpURLConnection class to send an HTTP GET request to Google.com to get the search result:
package net.javaguides.network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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://www.google.com/search?q=javaguides";
public static void main(String[] args) throws IOException {
sendHttpGETRequest();
}
private static void sendHttpGETRequest() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.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 not worked");
}
for (int i = 1; i <= 8; i++) {
System.out.println(httpURLConnection.getHeaderFieldKey(i) + " = " + httpURLConnection.getHeaderField(i));
}
}
}
Output:
GET Response Code :: 200
Google search result ....
Date = Tue, 14 May 2019 08:50:16 GMT
Expires = -1
Cache-Control = private, max-age=0
Content-Type = text/html; charset=UTF-8
P3P = CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server = gws
X-XSS-Protection = 0
X-Frame-Options = SAMEORIGIN
HttpURLConnection Class - Java HTTP POST Request Example
In this example, we use HttpURLConnection class to send an HTTP POST request to http://localhost:8080/login-jsp-jdbc-mysql-example/login.jsp link.
To test POST HTTP request, I am using a sample project from login-jsp-jdbc-mysql-tutorial because it has a login form with POST HTTP method. I have deployed it on my localhost tomcat server.
Here is a complete Java program to send Http Post request:
package net.javaguides.network;
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 POST_URL = "http://localhost:8080/login-jsp-jdbc-mysql-example/login.jsp";
private static final String POST_PARAMS = "userName=Ramesh&password=Pass@123";
public static void main(String[] args) throws IOException {
sendPOST();
}
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = httpURLConnection.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.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 not worked");
}
}
}
Note: If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. Rest all the steps will be the same as above, HttpsURLConnection will take care of SSL handshake and encryption.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment