URL Encoding/Decoding using Base64 in Java
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss.(Base 64 format reference).
The URL encoding is the same as Basic encoding the only difference is that it encodes or decodes the URL and Filename safe Base64 alphabet and does not add any line separation.
URL encoding
String encodedURL = Base64.getUrlEncoder()
.encodeToString(actualURL_String.getBytes());
Explanation: In above code we called Base64.Encoder using getUrlEncoder() and then get the encoded URLstring by passing the byte value of actual URL in encodeToString() method as parameter.
URL decoding
byte[] decodedURLBytes = Base64.getUrlDecoder().decode(encodedURLString);
String actualURL= new String(decodedURLBytes);
Explanation: In above code we called Base64.Decoder using getUrlDecoder() and then decoded the URL string passed in decode() method as parameter then convert return value to actual URL.
Below programs illustrate the Encoding and Decoding URL in Java:
Program 1: URL encoding using Base64 class.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
String sampleURL = "https:// www.geeksforgeeks.org/" ;
System.out.println( "Sample URL:\n"
+ sampleURL);
String encodedURL = Base64.getUrlEncoder()
.encodeToString(sampleURL.getBytes());
System.out.println( "encoded URL:\n"
+ encodedURL);
}
}
|
Output:
Sample URL:
https://www.geeksforgeeks.org/
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
Program 2: URL decoding using Base64 class.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
String encoded = "aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv" ;
System.out.println( "encoded URL:\n"
+ encoded);
byte [] actualByte = Base64.getUrlDecoder()
.decode(encoded);
String actualURLString = new String(actualByte);
System.out.println( "actual String:\n"
+ actualURLString);
}
}
|
Output:
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
actual String:
https://www.geeksforgeeks.org/
References:
Last Updated :
30 Jul, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...