Java
Integrate the Flimpa API into your Java applications.
Installation
This example uses the native Java 11+ HttpClient. No external dependencies are required, though you may prefer a library like OkHttp for easier multipart form data handling.
Initialization
Set up your API key and base URL.
java
private static final String API_KEY = "your_api_key";
private static final String BASE_URL = "https://api.flimpa.com/api/v1";Authentication
Authenticate your requests using the X-API-Key header for task creation, and the X-Task-Access-Token header for status and download requests.
Usage Example
This example demonstrates how to create a task, poll for its status, and download the result. Operations supported are compress-pdf and image-to-webp.
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.time.Duration;
public class FlimpaClient {
private static final String API_KEY = "your_api_key";
private static final String BASE_URL = "https://api.flimpa.com/api/v1";
private static final HttpClient client = HttpClient.newHttpClient();
public static void main(String[] args) throws Exception {
// 1. Create Task (Upload)
// (Requires multipart builder, omitted for brevity. See OkHttp or Apache HttpClient for simpler multipart)
// ... obtain taskId and accessToken ...
String taskId = "550e8400-e29b-41d4-a716-446655440000";
String accessToken = "1735689600000.a1b2c3d4e5f6...";
// 2. Poll Status
int delay = 1000;
while (true) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/tasks/" + taskId))
.header("X-Task-Access-Token", accessToken)
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String body = response.body();
if (body.contains("\"status\":\"COMPLETED\"")) break;
if (body.contains("\"status\":\"FAILED\"")) throw new RuntimeException("Task failed");
Thread.sleep(delay);
delay = Math.min(delay * 2, 10000);
}
// 3. Download Result
HttpRequest downloadReq = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/tasks/" + taskId + "/download"))
.header("X-Task-Access-Token", accessToken)
.GET()
.build();
HttpResponse<Path> downloadRes = client.send(downloadReq, HttpResponse.BodyHandlers.ofFile(Path.of("output.pdf")));
if (downloadRes.statusCode() >= 400) {
throw new RuntimeException("Failed to download result");
}
System.out.println("Success!");
}
}Error Handling
Always check the response status and handle potential errors. The API returns JSON with error and code fields when a request fails.
Best Practices
- Implement exponential backoff for polling (as shown in the example).
- Files are limited to 20MB.
- Tasks have a TTL of 1 hour. Download your results promptly.
- Do not expose your API key in client-side code.
Webhooks
Webhooks for task completion are Coming Soon. For now, please use polling.