Url编码
对字符进行编码,浏览器发送数据给服务器时使用的编码方法,但传递数据为中文、日文等其他不能识别的字符时,则需要编码后传递,在编码时,每个字之间使用%分隔,以便识别;编码时只有a-z、A-Z、0-9、"-"、"_"、"."、"*"不会被处理;解码时只识别%进行节码
//URL编码
public class Demo1 {
public static void main(String[] args) {
//URLEncode类:进行url编码操作
//URLDecode类:进行url解码操作
//编码处理
try {
String keyword = "雅马哈";
String encodeRet = URLEncoder.encode(keyword, "utf-8");
System.out.println("编码后"+encodeRet);
//解码处理
String decodeRet = URLDecoder.decode("%E9%9B%85%E9%A9%AC%E5%93%88", "utf-8");
System.out.println("解码后"+decodeRet);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
由于URLEncode类的改造函数是私有的,所以我们只能通过类名调用其中的方法;
注意事项:
- 编码时,只需要对中文内容进行处理
- 解码时,可以整个url进行处理
base64编码
对字节进行编码,把任意长度的二进制数据变为纯文本(更利于在某些协议下进行传输),并且编码后只包含a-z、A-Z、0-9、+、/、=,把3字节的二进制数据按6bit一组,用4个两位数表示,并转换成字符;共64种表示,其中,0-25:A-Z,26-51:a-z,52-61:0-9,62:+,63:/。是一种通用编码。缺点:编码后长度会增加1/3
//base64编码
public class Demo2 {
public static void main(String[] args) {
//原始字节数组
byte[] buf = {(byte)0xe4,(byte)0xb8,(byte)0xad};
//基于base64进行编码
String base64EncodeRet = Base64.getEncoder().encodeToString(buf);
System.out.println(base64EncodeRet);
//基于base64进行解码
byte[] base64DecodeRet = Base64.getDecoder().decode(base64EncodeRet);
//System.out.println(base64DecodeRet);
System.out.println(Arrays.toString(base64DecodeRet));
//基于base64进行解码
byte[] bytrArrayRet = Base64.getDecoder().decode("5LiT");
for(byte b : bytrArrayRet) {
System.out.println(Integer.toHexString(b));
}
}
}
在第一次基于base64编码后,得到5LIT这个字符,仍需使用base64对这个字符进行解码。
使用base64编码对图片进行编码以及还原
//将图片按照base64解码后进行保存
public class Demo3 {
public static void main(String[] args) {
//读取一张图片的原始字节内容
try {
byte[] imagebuf = Files.readAllBytes(Paths.get("E:\\猿究院\\20230710\\1.jpg"));
//按照Base64进行编码,并写入本地文件
String base64ImgRet = Base64.getEncoder().encodeToString(imagebuf);
Files.write(Paths.get("E:\\猿究院\\20230710\\1.txt"), base64ImgRet.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//将base64编码的字符串,解码为一张照片
public class Demo4 {
public static void main(String[] args) {
try {
//从文件中读取base64编码内容,并还原为字符串
byte[] strbyte = Files.readAllBytes(Paths.get("E:\\猿究院\\20230710\\1.txt"));
String baseImg = new String(strbyte);
//base64编码的字符串进行解码,解码后的原始字符串内容,保存成图片
byte[] base64Img = Base64.getDecoder().decode(baseImg);
Files.write(Paths.get("E:\\猿究院\\20230710\\c1.jpg"), base64Img);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
因为Base64编码后会出现+以及/,不符合URl的编码规则,会导致部分内容·不能使用,所以有一种针对于URl传输的Base64编码方会将/转换成"_",将+转换成"-"。
//将原始字节内容处理为适合URl传递的Base64编码
public class Demo5 {
public static void main(String[] args) {
//原始字节内容
byte[] input = new byte[] {0x01,0x02,0x7f,0x00};
//默认base64编码
String ret1 = Base64.getEncoder().encodeToString(input);
System.out.println("解码前:"+Arrays.toString(input));
System.out.println("解码后:"+ret1);
//基于URl的Base64编码
String ret2 = Base64.getUrlEncoder().encodeToString(input);
System.out.println("解码前:"+Arrays.toString(input));
System.out.println("解码后"+ret2);
}
}