Site icon

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:

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
Exit mobile version