In Java-based test frameworks, HTTP utilities are essential for driving API tests, managing test data, and integrating with UI flows. Whether you're using HttpClient, Rest Assured, or Playwright for Java, these utilities form the backbone of backend testing.
In modern test automation — especially when validating APIs, microservices, or integrating UI with backend — having robust HTTP utilities is critical.
Whether you're using Playwright, Rest Assured, or a custom CLI runner, HTTP utilities help you:
Send requests (GET, POST, PUT, DELETE)
Handle auth tokens, headers, cookies
Parse and validate responses
Mock, intercept, or replay traffic for testing
✅ 1. HTTP Client Wrapper
A reusable class or service to send HTTP requests with configurable:
Method (GET/POST/etc.)
URL
Headers
Payload (JSON/XML/form)
Timeout, retries
public HttpResponse sendPost(String url, Map<String, String> headers, String jsonBody) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.headers(headers.entrySet().stream().flatMap(e -> Stream.of(e.getKey(), e.getValue())).toArray(String[]::new))
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
✅ 2. Token & Session Management
Centralize auth:
Store login tokens (e.g., JWT) in context
Reuse across commands or tests
Auto-refresh or re-authenticate on 401
✅ 3. Response Parsing Helpers
Utility methods to:
Deserialize JSON into POJOs
Extract fields via JSONPath or simple maps
Validate status, schema, headers
Map<String, Object> jsonMap = new ObjectMapper().readValue(response.body(), Map.class);
✅ 4. Request Logging & Debugging
Log full request and response:
URL, method, headers, body, status
Timing info
Curl reproduction commands (optional)
✅ 5. Mocking / Intercept Support
Intercept outgoing requests:
For local dev (using WireMock, MockServer, or Playwright’s network hooks)
For contract testing or simulating errors
Run smoke or health checks as part of CLI or CI test flows
Setup test data (users, configs) via API before UI tests (e.g., create a user via API, then login via UI)
Extract tokens or IDs from responses and reuse them across steps
Validate backend response structure before asserting on UI
Chain requests and responses (login → create → validate → delete)
java.net.http.HttpClient (Java 11+) — built-in
Rest Assured — fluent REST testing DSL
Jackson / Gson — JSON parsing
TestNG or JUnit — assertions and test structure
WireMock — mock API server for isolation or failure simulation
🔍 Scenario:
Send a POST request to /login with JSON payload, receive a 200 OK, and extract the token from the JSON response.
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class RestAssuredExample {
public static void main(String[] args) {
RestAssured.baseURI = "https://api.example.com";
Response response = RestAssured
.given()
.contentType("application/json")
.body("{\"username\":\"admin\",\"password\":\"pass123\"}")
.when()
.post("/login")
.then()
.statusCode(200)
.extract()
.response();
String token = response.jsonPath().getString("token");
System.out.println("Token: " + token);
}
}
✅ Pros:
Fluent syntax
Built-in JSONPath
Cleaner for tests
Schema validation support
import java.net.http.*;
import java.net.URI;
import java.util.Map;
import com.fasterxml.jackson.databind.*;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
String json = "{\"username\":\"admin\",\"password\":\"pass123\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/login"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(response.body(), Map.class);
String token = (String) map.get("token");
System.out.println("Token: " + token);
} else {
System.err.println("Failed: " + response.statusCode());
}
}
}
✅ Pros:
Standard Java (no extra dependencies)
Great for internal libraries or production-grade apps
Flexible for custom HTTP logic (timeouts, redirects, retries)
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.ClassicHttpResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class ApacheHttpClientExample {
public static void main(String[] args) throws IOException {
String url = "https://api.example.com/login";
String json = "{\"username\":\"admin\", \"password\":\"pass123\"}";
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(json));
ClassicHttpResponse response = client.executeOpen(null, post, null);
int status = response.getCode();
if (status == 200) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> responseMap = mapper.readValue(response.getEntity().getContent(), Map.class);
String token = (String) responseMap.get("token");
System.out.println("✅ Token: " + token);
} else {
System.err.println("❌ Request failed with status: " + status);
}
}
}
}
Use Rest Assured when:
You’re writing test automation
You need clean assertions, schema checks, or fluent chaining
You prefer a high-level API focused on readability
Use HttpClient when:
You want a dependency-free, standard Java solution. zero dependencies (just JDK 11+)
You're writing lightweight tests, CLI tools, or internal scripts
You're building low-level frameworks or custom CLI/test runners
You value simplicity and cleaner code
You need fine-grained control over request/response handling
Use Apache HttpClient if:
You're building enterprise apps or complex HTTP clients
You need features like:
connection reuse
proxy routing
retry logic
cookie management
✅ Java HttpClient is great for basic REST calls in frameworks or CLI runners.
✅ Apache HttpClient is great when you need full control over HTTP behaviors.