Java Base64 URL Encoding Example

In this source code example, we show you how to encode (Base64) any URL in Java using the Base64 API that was introduced in Java 8.

The basic Base64.getEncoder() method provided by the Base64 API uses the standard Base64 alphabet that contains characters A-Z, a-z, 0-9, +, and /.

Since + and / characters are not URL and filename safe, The RFC 4648 defines another variant of Base64 encoding whose output is URL and Filename safe. This variant replaces + with a minus (-) and / with an underscore (_). Java contains an implementation of this variant as well. 

Java Base64 URL Encoding Example

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

class Base64DecodeExample {

    private static String base64UrlEncode(String value) {
        try {
            return Base64.getUrlEncoder()
                    .encodeToString(value.getBytes(StandardCharsets.UTF_8.toString()));
        } catch(UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

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

        String encodedData = base64UrlEncode(data);

        System.out.println("encodedData -> " + encodedData);
    }
}
Output:
encodedData -> aHR0cHM6Ly93d3cuc291cmNlY29kZWV4YW1wbGVzLm5ldC9zZWFyY2g_cT1qYXZh


Comments