Decode Base64 Async Responses in Java
Learn to decode Base64-encoded binary responses from ScraperAPI Async in Java. Process PDFs, images, and files with Java and command-line examples.
The responses returned by the Async API for binary requests require you to decode the data as they are encoded using Base64
encoding. This allows the binary data to be sent as a text string, which can then be decoded back into its original form when you want to use it.
Example request:
try {
String apiKey = "API_KEY";
String urlString = "https://async.scraperapi.com/jobs";
String jsonInputString = "{\"apiKey\": \"" + apiKey + "\", \"url\": \"https://pdfobject.com/pdf/sample.pdf\"}";
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Code: " + responseCode);
System.out.println("Response: " + response.toString());
} catch (Exception e) {e.printStackTrace();
}
}
}
Decode response:
import java.io.*;
import java.net.*;
import java.util.Base64;
public class ApiCall {
public static void main(String[] args) {
try {
URL url = new URL("https://async.scraperapi.com/jobs/<JOB_ID>");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = in.readLine();
in.close();
String base64EncodedBody = response.split("\"base64EncodedBody\":\"")[1].split("\"}")[0];
base64EncodedBody = base64EncodedBody.replaceAll("[^A-Za-z0-9+/=]", "");
try (FileOutputStream fos = new FileOutputStream("name.pdf")) {
fos.write(Base64.getDecoder().decode(base64EncodedBody));
}
System.out.println("PDF saved as name.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
PreviousRequest Async Batch Scraping with ScraperAPI in JavaNextScraperAPI Structured Data Collection in Java
Last updated
Was this helpful?