Base64 Encode decode URL/URI string in Java 8

Problem Statement ?

Given URL  (Uniform Resource Locator) or URI, we would like to encode URL to Base64 and decode Base64 encoded back to original URL 0r URL.

Example of Base64 Encoding and decoding of URL:

  1. URL  = “https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html”.
  2. Base64 encoded URL should: “aHR0cHM6Ly9kb2NzLm9yYWNsZS5jb20vamF2YXNlLzgvZG9jcy9hcGkvamF2YS91dGlsL0Jhc2U2NC5EZWNvZGVyLmh0bWw=”
  3. If decode Base64 encoded URL (Step 2), then we would get original URL back (Step number 1) “https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html”

JDK classes for Base 64 encoding & decoding:

  • Base64 class has two inner classes Encoder and Decoder which are used to encode and decode input byte data respectively.
  • We have discussed the Base64 encoding and decoding of String with and withoutPadding using Encoder and Decoder classes.
  • Encoder class:

    • Encoder class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
    • Instances of Base64.Encoder class are SAFE for use by multiple concurrent threads.
  • Decoder class:

    • Decoder class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
    • Instances of Base64.Decoder class are SAFE for use by multiple concurrent threads.

Code: Encode & decode URL using Base64 (Java8)

package org.learn;

import java.util.Base64;

public class Base64URLEncodeDemo {

    public static void main(String[] args) {
        String input = "https://docs.oracle.com/javase/8/docs/api/java/" +
                "util/Base64.Decoder.html";
        byte[] bytesInput = input.getBytes();

        System.out.println("URL : "+input);

        //Encode URL to Base64
        Base64.Encoder base64Encoder = Base64.getUrlEncoder();
        String encodedString = base64Encoder.encodeToString(bytesInput);
        System.out.println("Encoded URL :" + encodedString);

        //Decode Base64 encoded URL to URL
        Base64.Decoder base64Decoder = Base64.getUrlDecoder();
        byte[] byteDecoded = base64Decoder.decode(encodedString);
        System.out.println("Decoded URL :" + new String(byteDecoded));
    }
}

Output: Encode & decode of URL/URI  (Base64 / Java8)

URL : https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
Encoded URL :aHR0cHM6Ly9kb2NzLm9yYWNsZS5jb20vamF2YXNlLzgvZG9jcy9hcGkvamF2YS91dGlsL0Jhc2U2NC5EZWNvZGVyLmh0bWw=
Decoded URL :https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
Scroll to Top