Java Example
This example demonstrates how to call the Mockd API using the Java HttpClient (available in Java 11+) and use the returned results to call another method. This is helpful if you need to process mock data within a Java application or backend service.
Java Example
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class MockdJavaExample {
// A method that processes the data received from Mockd
public static void processUserData(String userData) {
System.out.println("Processing user data...");
System.out.println("Mockd API Response: " + userData);
// In a real application, you would typically use a library like Jackson or Gson
// to parse the JSON string into a Java object here.
}
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
// Define the JSON payload
String jsonPayload = """
{
"fields": {
"name": "male-full-name",
"email": "email"
}
}
""";
// Create the POST request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.mockd.info/"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
// Send the request asynchronously
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(MockdJavaExample::processUserData)
.join(); // Wait for completion
}
}
Explanation
processUserData(String userData): This is the method that is called with the results from the Mockd API. In a real-world scenario, you would parse the JSON response into a POJO (Plain Old Java Object) using a library like Jackson or Gson.HttpClient.newHttpClient(): We use the standard JavaHttpClientintroduced in Java 11 to make our request.HttpRequest.newBuilder(): We build aPOSTrequest, specifying the Mockd API URL and setting theContent-Typeheader toapplication/json.jsonPayload: We define the fields we want Mockd to generate using a Java Text Block (available in Java 15+).client.sendAsync(...): We send the request asynchronously. This is efficient as it doesn't block the main thread while waiting for the response..thenAccept(MockdJavaExample::processUserData): Once the response is received, we pass the body (the generated JSON) directly to ourprocessUserDatamethod.