|
| 1 | +package com.mkyong.java11.jep321; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.net.URI; |
| 5 | +import java.net.URLEncoder; |
| 6 | +import java.net.http.HttpClient; |
| 7 | +import java.net.http.HttpRequest; |
| 8 | +import java.net.http.HttpResponse; |
| 9 | +import java.nio.charset.StandardCharsets; |
| 10 | +import java.time.Duration; |
| 11 | +import java.util.HashMap; |
| 12 | +import java.util.Map; |
| 13 | + |
| 14 | +public class HttpClientPostForm { |
| 15 | + |
| 16 | + private static final HttpClient httpClient = HttpClient.newBuilder() |
| 17 | + .version(HttpClient.Version.HTTP_2) |
| 18 | + .connectTimeout(Duration.ofSeconds(10)) |
| 19 | + .build(); |
| 20 | + |
| 21 | + public static void main(String[] args) throws IOException, InterruptedException { |
| 22 | + |
| 23 | + // form parameters |
| 24 | + Map<Object, Object> data = new HashMap<>(); |
| 25 | + data.put("username", "abc"); |
| 26 | + data.put("password", "123"); |
| 27 | + data.put("custom", "secret"); |
| 28 | + data.put("ts", System.currentTimeMillis()); |
| 29 | + |
| 30 | + HttpRequest request = HttpRequest.newBuilder() |
| 31 | + .POST(ofFormData(data)) |
| 32 | + .uri(URI.create("https://httpbin.org/post")) |
| 33 | + .setHeader("User-Agent", "Java 11 HttpClient Bot") // add request header |
| 34 | + .header("Content-Type", "application/x-www-form-urlencoded") |
| 35 | + .build(); |
| 36 | + |
| 37 | + HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); |
| 38 | + |
| 39 | + // print status code |
| 40 | + System.out.println(response.statusCode()); |
| 41 | + |
| 42 | + // print response body |
| 43 | + System.out.println(response.body()); |
| 44 | + |
| 45 | + } |
| 46 | + |
| 47 | + // Sample: 'password=123&custom=secret&username=abc&ts=1570704369823' |
| 48 | + public static HttpRequest.BodyPublisher ofFormData(Map<Object, Object> data) { |
| 49 | + var builder = new StringBuilder(); |
| 50 | + for (Map.Entry<Object, Object> entry : data.entrySet()) { |
| 51 | + if (builder.length() > 0) { |
| 52 | + builder.append("&"); |
| 53 | + } |
| 54 | + builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8)); |
| 55 | + builder.append("="); |
| 56 | + builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8)); |
| 57 | + } |
| 58 | + return HttpRequest.BodyPublishers.ofString(builder.toString()); |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments