Java Base64 URL Encode and Decode Example

1. Introduction

Base64 URL encoding and decoding are commonly used techniques to safely transmit data over networks in a URL-safe format by encoding potentially problematic characters. Java provides built-in support for Base64 encoding and decoding, including a variant for URL and Filename safe encoding.

Key Points

1. Base64 URL encoding modifies the output of standard Base64 encoding to make it safe for URLs and filenames.

2. Base64.getUrlEncoder() and Base64.getUrlDecoder() are used for URL-safe encoding and decoding.

3. The methods handle encoding and decoding using UTF-8 charset, ensuring compatibility across different systems.

2. Program Steps

1. Import necessary classes.

2. Create methods for Base64 URL encoding and decoding.

3. Encode a URL string and then decode it back to verify the process.

3. Code Program

import java.nio.charset.StandardCharsets;
import java.util.Base64;

class Base64UrlCodecExample {

    private static String base64UrlDecode(String value) {
        byte[] decodedValue = Base64.getUrlDecoder().decode(value);
        return new String(decodedValue, StandardCharsets.UTF_8);
    }

    private static String base64UrlEncode(String value) {
        return Base64.getUrlEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args) {
        String data = "https://www.sourcecodeexamples.net/search?q=java";

        String encodedData = base64UrlEncode(data);
        System.out.println("encodedData -> " + encodedData);

        String decodedData = base64UrlDecode(encodedData);
        System.out.println("decodedData -> " + decodedData);
    }
}

Output:

encodedData -> aHR0cHM6Ly93d3cuc291cmNlY29kZWV4YW1wbGVzLm5ldC9zZWFyY2g_cT1qYXZh
decodedData -> https://www.sourcecodeexamples.net/search?q=java

Explanation:

1. Base64.getUrlEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8)): This line encodes the given URL string into a Base64 encoded string that is safe for use in URLs. The UTF_8 charset ensures that the encoding handles any special characters in the URL correctly.

2. Base64.getUrlDecoder().decode(value): This line decodes the previously encoded string back into its original format. The decoding process reverses the encoding, proving that the encoded data can be reliably turned back into its original form.

3. The output demonstrates that the original URL is successfully encoded into a Base64 URL-safe string and then decoded back to the original URL, showcasing the effectiveness of Java's Base64 URL encoding and decoding functionality.


Comments