Java Programming Tutorials

Java programming tutorials with many code examples!

Java Base64 URL


How to use Java Base64 to encode data using URL and Filename safe Base64 Alphabet? In the following example we’ll show how to use Base64 util class, available since Java 8.


In last two posts we’ve shown how to use java.util.Base64 class to work with basic and MIME types of Base64. Here we’ll show how to encode safely for URL and Filename purposes. To do this we’ll use Base64.getUrlEncoder() to create an URL/Filename safe encoder and Base64.getUrlDecoder() for decoder:


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

public class Base64URLEncoder {

    public static void main(String[] args) {
        String message = "This will be encoded using URL and Filename safe Base64 Alphabet!";
        System.out.println("Original: " + message);

        byte[] bytesToEncode = message.getBytes(StandardCharsets.UTF_8);

        byte[] encoded = encode(bytesToEncode);


    private static byte[] encode(byte[] bytesToEncode) {
        Base64.Encoder encoder = Base64.getUrlEncoder();
        byte[] encoded = encoder.encode(bytesToEncode);
        System.out.println("Encoded: " + new String(encoded));
        return encoded;

    private static void decode(byte[] encoded) {
        Base64.Decoder decoder = Base64.getUrlDecoder();
        byte[] decoded = decoder.decode(encoded);
        System.out.println("Decoded: " + new String(decoded));

And here’s the result of running the above code:

Original: This will be encoded using URL and Filename safe Base64 Alphabet!
Decoded: This will be encoded using URL and Filename safe Base64 Alphabet!

As you can see UrlEncoder adds no newline at the end. It also rejects data that contains characters outside of the Base64 Alphabet.

Was it helpful? Share!