Class FreeImageHostClient

java.lang.Object
com.serinity.accesscontrol.service.FreeImageHostClient

public class FreeImageHostClient extends Object
Utility client responsible for uploading image files to FreeImage.host using its HTTP API.

This class provides a centralized and static mechanism for sending multipart/form-data HTTP POST requests to the FreeImage.host image upload endpoint. The API key and request URL are loaded from environment variables via EnvironmentVariableLoader.

The client uses Java's HttpClient to construct and execute HTTP requests. Images are uploaded as raw byte arrays within a manually constructed multipart request body.

Configuration:

  • IMAGE_API_KEY – Retrieved from environment variables.
  • IMAGE_REQUEST_URL – Retrieved from environment variables.

Exposed functionality:

The upload process:

  1. Validates that the provided file exists.
  2. Reads the file into memory as a byte array.
  3. Constructs a multipart/form-data request body with a unique boundary.
  4. Sends the request to the FreeImage.host API using HttpClient.
  5. Parses the JSON response to extract the public image URL.

The JSON parsing is performed manually using string operations and brace matching to locate the "image" object and extract its "url" field. Escape sequences (e.g., \/) are cleaned before returning the final URL.

Example usage:

File image = new File("profile.png");
String imageUrl = FreeImageHostClient.uploadImage(image);
System.out.println("Uploaded image URL: " + imageUrl);

Exceptions:

Note:

  • The entire file is loaded into memory before upload; large files may impact memory usage.
  • Environment variables must be properly configured; otherwise, the upload request will fail.
  • For production-grade systems, consider using a JSON parser library instead of manual string parsing.
Since:
2026-02-16
Version:
1.0
Author:
@ZouariOmar (zouariomar20@gmail.com)
See Also:
  • Constructor Details

    • FreeImageHostClient

      public FreeImageHostClient()
      Creates a new FreeImage.host client holder.
  • Method Details

    • uploadImage

      public static String uploadImage(File imageFile) throws IOException, InterruptedException
      Uploads an image file to FreeImage.host and returns the public URL.
      Parameters:
      imageFile - image file to upload
      Returns:
      publicly accessible image URL
      Throws:
      IOException - if reading the file or HTTP transport fails
      InterruptedException - if the upload request is interrupted
    • extractImageUrl

      public static String extractImageUrl(String jsonResponse)
      Extracts "url" field from FreeImage.host JSON response using regex.
      Parameters:
      jsonResponse - raw JSON API response
      Returns:
      extracted image URL