McAPI - Screenshot API Java

Java sample code to capture website screenshots with the McAPI Screenshot REST API service. The sample uses Java 11 LTS but will also work with more recent versions. It will not work with Java 8 or older LTS versions. Jackson is required for building the JSON payload of the request.

Requirements: A free RapidAPI account. Replace YOUR_API_KEY in the code below with your RapidAPI key.

The sample code works with the free tier of the API, see RapidAPI McAPI Barcode Listing for available plans.

See the overview page for a reference that lists all available parameters and error codes.

Take a screenshot using Java with HttpClient module

In this Java program we take a screenshot of the Indiehackers website. The device is set to Default (=1024x768px). With the storeExternal option set to "false", the screenshot will be returned as a base64 encoded JPEG.

The source code:

// Java

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

class Screenshot {

    public static void main(String[] args) throws IOException, InterruptedException {

    Map<String, Object> json = new HashMap<String, Object>();
    json.put("url", "https://indiehackers.com");
    json.put("format", "jpeg");
    json.put("storeExternal", "false");
    json.put("devices", new String[] {"Default"});
    
    String postData = new ObjectMapper().writeValueAsString(json);

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://mcapi-screenshot.p.rapidapi.com/"))
        .header("content-type", "application/json")
        .header("x-rapidapi-host", "mcapi-screenshot.p.rapidapi.com")
        .header("x-rapidapi-key", "YOUR_API_KEY")
        .method("POST", HttpRequest.BodyPublishers.ofString(postData))
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.body());
}

The response will be delivered as a JSON object in body, e.g.:

{
  service: "McAPI Screenshot Generator, https://mcapi.io",
  version: "V1",
  url: "https://indiehackers.com",
  screenshots: [
    {
      device: "Default",
      screenshot: "data:image/jpeg;base64,/9j/4AAQSkZJRgAB ... 9yXvZG0pSuhyP/9k="
    }
  ]
}

McAPI Screenshot API - Sample screenshot with Java

The returned image from the Java program:

Image of McAPI Screenshot API Sample Screenshot Java

Back to McAPI Screenshot API main page.