View all our code samples

Using OkHttp in Java

OkHttp is a popular HTTP client library for Java and Android. It provides a simple and intuitive API for making HTTP requests and processing responses. OkHttp supports features like connection pooling, caching, interceptors, and asynchronous requests.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Java:

import okhttp3.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PDFShift {

    private static final OkHttpClient client = new OkHttpClient();

    public static byte[] convert(String apiKey, String params, String endpoint) throws Exception {
        if (!endpoint.equals("pdf") && !endpoint.equals("png") && !endpoint.equals("jpg") && !endpoint.equals("webp")) {
            throw new IllegalArgumentException("Invalid endpoint");
        }

        String url = "https://api.pdfshift.io/v3/convert/" + endpoint;
        
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, params);
        Request request = new Request.Builder()
            .url(url)
            .method("POST", body)
            .addHeader("Authorization", Credentials.basic("api", apiKey))
            .addHeader("Content-Type", "application/json")
            .build();

        byte[] content;
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            content = response.body().bytes();
        }

        if (params.contains("\"filename\"") || params.contains("\"webhook\"")) {
            return new Gson().fromJson(new String(content.toByteArray()), JsonObject.class).toString().getBytes();
        }

        return content;
    }
}

Here's how you can use the above code:

public static void main(String[] args) throws Exception {
    String apiKey = "sk_XXXXXXXXXXXXXX";
    String params = "{\"source\" : \"https://en.wikipedia.org/wiki/REST\"}";
    String endpoint = "pdf";

    byte[] result = convert(apiKey, params, endpoint);
    Files.write(Paths.get("result.pdf"), result);
}

We've tested this code with the latest version of OkHttp and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.