How to Take a Screenshot of a URL using Java
Whether you’re trying safely investigate a potentially threatening URL, or simply trying to document the client-side view of a specific web page, there’s an easy way to get the job done programmatically. Using our URL screenshot API, you can quickly generate a PNG image of any input URL; this operation will fully & securely render the website (JavaScript, HTML5, CSS & other advanced features are supported) and subsequently return the image encoding string.
You can easily take advantage of this API using the Java code examples below to structure your API call. It’s free to use — just register a free account on our website & use your secure API key to authenticate within the appropriate parameter.
We can kick off the process by installing the API client with Maven. Start by adding a reference to the pom.xml repository:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Next, we can add a reference to the pom.xml dependency:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>
With installation complete, we can shift focus to the controller & add the following imports to the top of our file:
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.ConvertWebApi;
Lastly, we can call the API as shown below, and include our API key where indicated in the comments:
ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");ConvertWebApi apiInstance = new ConvertWebApi();
ScreenshotRequest input = new ScreenshotRequest(); // ScreenshotRequest | Screenshot request parameters
try {
byte[] result = apiInstance.convertWebUrlToScreenshot(input);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertWebApi#convertWebUrlToScreenshot");
e.printStackTrace();
}
That just about does it — no more code is required. If you want to convert your image to another format, you can easily do so by including one of our Image format conversion APIs (available via the Cloudmersive Image Conversion API endpoint).