In this source code example, we will write a Java program that uses HTTP Client API to submit form data (application/x-www-form-URL-encoded).
Java 11 HttpClient didn’t provide API for the form data, we have to construct it manually.Java HttpClient POST 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"
}
Comments
Post a Comment