Java 使用Base64对URL进行编码/解码
Base 64是一种编码方案,它将二进制数据转换为文本格式,这样编码后的文本数据可以很容易地在网络上传输而不被破坏,也没有任何数据损失。(Base 64格式参考)。
URL编码与Basic编码相同,唯一的区别是它对URL和文件名进行安全的Base64字母编码或解码,并且不添加任何行的分隔。
URL 编码
String encodedURL = Base64.getUrlEncoder() .encodeToString(actualURL_String.getBytes());
解释: 在上面的代码中,我们使用getUrlEncoder()调用了Base64.Encoder,然后通过在encodeToString()方法中传递实际URL的字节值作为参数来获得编码后的URL字符串。
URL解码
byte[] decodedURLBytes = Base64.getUrlDecoder().decode(encodedURLString);String actualURL= new String(decodedURLBytes);
解释: 在上面的代码中,我们使用getUrlDecoder()调用Base64.Decoder,然后对decode()方法中作为参数传递的URL字符串进行解码,然后将返回值转换成实际的URL。
以下程序说明了在Java中对URL进行编码和解码的情况。
程序1: 使用Base64类进行URL编码。
// Java program to demonstrate// URL encoding using Base64 class import java.util.*;public class GFG { public static void main(String[] args) { // create a sample url String to encode String sampleURL = "https:// www.geeksforgeeks.org/"; // print actual URL String System.out.println("Sample URL:\n" + sampleURL); // Encode into Base64 URL format String encodedURL = Base64.getUrlEncoder() .encodeToString(sampleURL.getBytes()); // print encoded URL System.out.println("encoded URL:\n" + encodedURL); }}
输出:
Sample URL:https://www.geeksforgeeks.org/encoded URL:aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
程序2: 使用Base64类对URL进行解码。
// Java program to demonstrate// Decoding Basic Base 64 format to String import java.util.*;public class GFG { public static void main(String[] args) { // create a encoded URL to decode String encoded = "aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv"; // print encoded URL System.out.println("encoded URL:\n" + encoded); // decode into String URL from encoded format byte[] actualByte = Base64.getUrlDecoder() .decode(encoded); String actualURLString = new String(actualByte); // print actual String System.out.println("actual String:\n" + actualURLString); }}输出:
encoded URL:aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcvactual String:https://www.geeksforgeeks.org/
参考资料
https://docs.oracle.com/javase/10/docs/api/java/util/Base64.htmlhttps://www.geeksforgeeks.org/decode-encoded-base-64-string-ascii-string/https://www.geeksforgeeks.org/encode-ascii-string-base-64-format/