How do I build an HttpRequest with query parameters?

In Java 11, you can use the HttpRequest class (from the java.net.http package) to build HTTP requests, including adding query parameters to a URI.

Here’s how you can build an HttpRequest with query parameters:

Example

package org.kodejava.net.http;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpHeaders;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpRequestExample {

   public static void main(String[] args) throws Exception {
      // Base URI
      String baseUri = "https://example.com/api";

      // Query Parameters
      Map<String, String> queryParams = Map.of(
              "_param1", "value1",
              "_param2", "value2",
              "_param3", "value3"
      );

      // Build the URI with query parameters
      String uriWithParams = buildUriWithQueryParams(baseUri, queryParams);

      // Create the HttpRequest
      HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(uriWithParams))
              .GET()
              .build();

      // Print Request Information
      System.out.println("Request URI: " + request.uri());

      // Send the HTTP request (optional, for demo purposes)
      HttpClient client = HttpClient.newHttpClient();
      HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
      System.out.println("Response Status Code: " + response.statusCode());
      System.out.println("Response Body: " + response.body());
   }

   private static String buildUriWithQueryParams(String baseUri, Map<String, String> queryParams) {
      StringBuilder uriBuilder = new StringBuilder(baseUri);

      if (!queryParams.isEmpty()) {
         uriBuilder.append("?");
         // Encode each query parameter
         queryParams.forEach((key, value) -> {
            uriBuilder
                    .append(URLEncoder.encode(key, StandardCharsets.UTF_8))
                    .append("=")
                    .append(URLEncoder.encode(value, StandardCharsets.UTF_8))
                    .append("&");
         });
         // Remove the trailing "&"
         uriBuilder.deleteCharAt(uriBuilder.length() - 1);
      }

      return uriBuilder.toString();
   }
}

Explanation

  1. Base URI: The starting point for the requested resource, e.g., `https://example.com/api`.
  2. Query Parameters: These are typically a set of key-value pairs added to the URI. In the example, we used the Map<String, String> to store the parameters.
  3. Encoding Parameters: The URLEncoder.encode(key, StandardCharsets.UTF_8) ensures that special characters in the keys or values (e.g., spaces, ampersands) are properly encoded.
  4. Build the Query String:
    • We check if there are query parameters to append.
    • Iterate through the Map, encode each key-value pair, and append them as a query string.
    • Remove the trailing ampersand (&) after adding all query parameters.
  5. Build the HttpRequest: We use the HttpRequest.newBuilder() to configure a GET request. You can change the HTTP method or add headers as needed (e.g., .header(key, value)).
  6. Send the Request: We use HttpClient to send the request and capture the response (optional for the example).

Sample Output

For baseUri = "https://example.com/api" and queryParams = {"_param1": "value1", "_param2": "value2", "_param3": "value3"}, the output would be:

Request URI: https://example.com/api?_param1=value1&_param2=value2&_param3=value3
Response Status Code: 200
Response Body: <response body here>

You can adapt this approach for POST requests or other configurations if needed.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.