DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Get Cell Data From an Excel Spreadsheet Using APIs in Java
  • JBang: How to Script With Java for Data Import From an API
  • Effective Java Collection Framework: Best Practices and Tips
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Trending

  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  1. DZone
  2. Coding
  3. Java
  4. How To Base64 Encode or Decode Content Using APIs in Java

How To Base64 Encode or Decode Content Using APIs in Java

This article offers some high-level background for base64 encoding and provides several free API solutions for detecting, encoding and decoding base64 content.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Jan. 21, 24 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
5.7K Views

Join the DZone community and get the full member experience.

Join For Free

Base64 encoding was originally conceived more than 30 years ago (named in 1992). Back then, the Simple Mail Transfer Protocol (SMTP) forced developers to find a way to encode e-mail attachments in ASCII characters so SMTP servers wouldn't interfere with them.

All these years later, Base64 encoding is still widely used for the same purpose: to replace binary data in systems where only ASCII characters are accepted. E-mail file attachments remain the most common example of where we use Base64 encoding, but it’s not the only use case. Whether we’re stashing images or other documents in HTML, CSS, or JavaScript, or including them in JSON objects (e.g., as a payload to certain API endpoints), Base64 simply offers a convenient, accessible solution when our recipient systems say “no” to binary.   

The Base64 encoding process starts with a binary encoded file — or encoding a file's content in binary if it isn't in binary already. The binary content is subsequently broken into groups of 6 bits, with each group represented by an ASCII character. There are precisely 64 ASCII characters available for this encoding process — hence the name Base64 — and those characters range from A-Z (capitalized), a-z (lower case), 0 – 9, +, and /. The result of this process is a string of characters; the phrase “hello world”, for example, ends up looking like “aGVsbG8gd29ybGQ=”. The “=” sign at the end is used as padding to ensure the length of the encoded data is a multiple of 4.

The only significant challenge with Base64 encoding in today’s intensely content-saturated digital world is the toll it takes on file size. When we Base64 encode content, we end up with around 1 additional byte of information for every 3 bytes in our original content, increasing the original file size by about 33%. In context, that means an 800kb image file we’re encoding instantly jumps to over 1mb, eating up additional costly resources and creating an increasingly cumbersome situation when we share Base64 encoded content at scale.

When our work necessitates a Base64 content conversion, we have a few options at our disposal. First and foremost, many modern programming languages now have built-in classes designed to handle Base64 encoding and decoding locally. Since Java 8 was initially released in 2014, for example, we’ve been able to use java.util.Base64 to handle conversions to and from Base64 with minimal hassle. Similar options exist in Python and C# languages, among others.

Depending on the needs of our project, however, we might benefit from making our necessary conversions to and from Base64 encoding with a low-code API solution. This can help take some hands-on coding work off our own plate, offload some of the processing burden from our servers, and in some contexts, deliver more consistent results. In the remainder of this article, I’ll demonstrate a few free APIs we can leverage to streamline our workflows for 1) identifying when content is Base64 encoded and 2) encoding or decoding Base64 content.

Demonstration

Using the ready-to-run Java code examples provided further down the page, we can take advantage of three separate free-to-use APIs designed to help build out our Base64 detection and conversion workflow. These three APIs serve the following functions (respectively):

  1. Detect if a text string is Base64 encoded
  2. Base64 decode content (convert Base64 string to binary content)
  3. Base64 encode content (convert either binary or file data to a Base64 text string)

A few different text encoding options exist out there, so we can use the first API as a consistent way of identifying (or validating) Base64 encoding when it comes our way. Once we’re sure that we’re dealing with Base64 content, we can use the second API to decode that content back to binary. When it comes time to package our own content for email attachments or relevant systems that require ASCII characters, we can use the third API to convert binary OR file data content directly to Base64. As a quick reminder, if we’re using a file data string, the API will first binary encode that content before Base64 encoding it, so we don’t have to worry about that part.

To authorize our API calls, we’ll need a free-tier API key, which will allow us a limit of 800 API calls per month (with no additional commitments — our total will simply reset the following month if/when we reach it).

Before we call the functions for any of the above APIs, our first step is to install the SDK.

In our Maven POM file, let’s add a reference to the repository (Jitpack is used to dynamically compile the library):

XML
 
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>


Next, let’s add a reference to the dependency:

XML
 
<dependencies>
<dependency>
    <groupId>com.github.Cloudmersive</groupId>
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
    <version>v4.25</version>
</dependency>
</dependencies>


Now we can implement ready-to-run code to call each independent API.  

Let’s start with the base64 detection API.  We can use the following code to structure our API call:

Java
 
// 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.EditTextApi;

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");

EditTextApi apiInstance = new EditTextApi();
Base64DetectRequest request = new Base64DetectRequest(); // Base64DetectRequest | Input request
try {
    Base64DetectResponse result = apiInstance.editTextBase64Detect(request);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditTextApi#editTextBase64Detect");
    e.printStackTrace();
}


Next, let’s move on to our base64 decoding API.  We can use the following code to structure our API call:

Java
 
// 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.EditTextApi;

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");

EditTextApi apiInstance = new EditTextApi();
Base64DecodeRequest request = new Base64DecodeRequest(); // Base64DecodeRequest | Input request
try {
    Base64DecodeResponse result = apiInstance.editTextBase64Decode(request);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditTextApi#editTextBase64Decode");
    e.printStackTrace();
}


Finally, let’s implement our base64 encoding option (as a reminder, we can use binary OR file data content for this one).  We can use the following code to structure our API call:

Java
 
// 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.EditTextApi;

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");

EditTextApi apiInstance = new EditTextApi();
Base64EncodeRequest request = new Base64EncodeRequest(); // Base64EncodeRequest | Input request
try {
    Base64EncodeResponse result = apiInstance.editTextBase64Encode(request);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditTextApi#editTextBase64Encode");
    e.printStackTrace();
}


Now we have a few additional options for identifying, decoding, and/or encoding base64 content in our Java applications. 

API Base64 Data (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How To Get Cell Data From an Excel Spreadsheet Using APIs in Java
  • JBang: How to Script With Java for Data Import From an API
  • Effective Java Collection Framework: Best Practices and Tips
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

OSZAR »