265. Handling form data

JDK 11's HTTP Client API doesn't come with built-in support for triggering POST requests with x-www-form-urlencoded. The solution to this problem is to rely on a custom BodyPublisher class.

Writing a custom BodyPublisher class is pretty simple if we consider the following:

  • Data is represented as key-value pairs
  • Each pair is a key = value type
  • Pairs are separated via the & character
  • Keys and values should be properly encoded

Since data is represented as key-value pairs, it's very convenient to store in Map. Furthermore, we just loop this Map and apply the preceding information, as follows:

public class FormBodyPublisher {

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);
}
}

Relying on this solution, a POST (x-www-form-urlencoded) request can be triggered as follows:

Map<Object, Object> data = new HashMap<>();
data.put("firstname", "John");
data.put("lastname", "Year");
data.put("age", 54);
data.put("avatar", "https://avatars.com/johnyear");

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
.header("Content-Type", "application/x-www-form-urlencoded")
.uri(URI.create("http://jkorpela.fi/cgi-bin/echo.cgi"))
.POST(FormBodyPublisher.ofForm(data))
.build();

HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());

In this case, the response is just an echo of the sent data. Depending on the server's response, the application needs to deal with it, as shown in the Handling response body types section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset