🎓 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
In this tutorial, we will see how to use Java 11 HttpClient API to submit form data and also we will see how to use Java 11 HttpClient API to send JSON data to the server.
Java 11 introduced a new standard HTTP client library called HttpClient that provides a more modern and flexible way to send HTTP requests and handle responses. The new HttpClient is designed to be more efficient, scalable, and capable than the legacy HttpURLConnection API, and supports both synchronous and asynchronous request processing.Java HttpClient POST Request Example - Send Form Data
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
Map<Object, Object> data = new HashMap<>();
data.put("fistname", "admin");
data.put("lastname", "admin");
data.put("age", 25);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.header("Content-Type", "application/x-www-form-urlencoded")
.uri(URI.create("https://httpbin.org/post"))
.POST(ofForm(data))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println("\n Body: " + response.body());
}
public static HttpRequest.BodyPublisher ofForm(Map<Object, Object> data) {
StringBuilder body = new StringBuilder();
for (Object dataKey : data.keySet()) {
if (body.length() > 0) {
body.append("&");
}
body.append(encode(dataKey))
.append("=")
.append(encode(data.get(dataKey)));
}
return HttpRequest.BodyPublishers.ofString(body.toString());
}
private static String encode(Object obj) {
return URLEncoder.encode(obj.toString(), StandardCharsets.UTF_8);
}
}
Output:
Status code: 200
Body: {
"args": {},
"data": "",
"files": {},
"form": {
"age": "25",
"fistname": "admin",
"lastname": "admin"
},
"headers": {
"Content-Length": "36",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Java-http-client/17.0.2",
"X-Amzn-Trace-Id": "Root=1-63070225-277b1f41012b39780e96a216"
},
"json": null,
"origin": "103.59.74.90",
"url": "https://httpbin.org/post"
}Java HttpClient POST Request JSON Example - Send JSON Data
This Java program uses HTTP Client API to submit form data in a JSON format(application/json).
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
// json formatted data
String json = new StringBuilder()
.append("{")
.append("\"firstName\":\"tom\",")
.append("\"lastName\":\"cruise\",")
.append("\"age\":\"50\"")
.append("}").toString();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.uri(URI.create("https://httpbin.org/post"))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println("\n Body: " + response.body());
}
}
Output:
Status code: 200
Body: {
"args": {},
"data": "{\"firstName\":\"tom\",\"lastName\":\"cruise\",\"age\":\"50\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "50",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "Java-http-client/17.0.2",
"X-Amzn-Trace-Id": "Root=1-63070480-32c7ceee01c7433d7dc18550"
},
"json": {
"age": "50",
"firstName": "tom",
"lastName": "cruise"
},
"origin": "103.59.74.90",
"url": "https://httpbin.org/post"
}Conclusion
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
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment