Advertisement
Intermediate Java, Java Networking & HTTP Client

How would you send URL-encoded form data (application/x-www-form-urlencoded) using HttpClient, as opposed to a JSON request body?

Short answer

Form-encoded data requires manually constructing the properly URL-encoded key=value&key2=value2 formatted string (using URLEncoder.encode() to correctly escape special characters in each individual key/value pair) and setting the Content-Type: application/x-www-form-urlencoded…

Save Java mock interview
Advertisement
AModel answer
Form-encoded data requires manually constructing the properly URL-encoded key=value&key2=value2 formatted string (using URLEncoder.encode() to correctly escape special characters in each individual key/value pair) and setting the Content-Type: application/x-www-form-urlencoded header explicitly, since HttpClient itself has no built-in form-encoding helper the way some other HTTP libraries provide -- this is commonly needed when interacting with older APIs or OAuth token endpoints that specifically expect this traditional form-encoded format rather than JSON.
Map<String, String> formData = Map.of("grant_type", "client_credentials", "client_id", "abc123");
String encodedBody = formData.entrySet().stream()
    .map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
    .collect(Collectors.joining("&"));

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://auth.example.com/oauth/token"))
    .header("Content-Type", "application/x-www-form-urlencoded")
    .POST(HttpRequest.BodyPublishers.ofString(encodedBody))
    .build();
Real-world example
An OAuth2 client requesting an access token from an authorization server manually constructs a URL-encoded form body (since OAuth2 token endpoints conventionally expect this format rather than JSON), correctly escaping each parameter value via URLEncoder to handle any special characters safely.
Likely follow-ups
  • Why do OAuth2 and many older web APIs specifically use form encoding rather than JSON for these particular requests?
  • What specific characters does URLEncoder.encode() escape, and why is manual string concatenation without encoding dangerous?
Related topics