日拱一卒:URL编码与解码

2023-02-03  本文已影响0人  Tinyspot

1. 字符集(Charset)

1.1 字符编码(Character Encoding)

1.2 转义符(escape character)

2. URL 编码与解码

2.1 URL 编码

URL 使用 key=value 键值对来传参,键值对之间以 & 符号分隔
value 值包含 = 或 &,会造成接收Url的服务器解析错误,所以需要对字符进行转义,即编码

@Test
public void test() throws UnsupportedEncodingException {
    String url = "/files/loadFile.html?attachIndex=https://cdn.xxx.com/this$*()*#.txt&fileName=this$*()*#.txt";
    String fileName = url.split("&fileName=")[1];
    // 编码  /files/loadFile.html?attachIndex=https://cdn.xxx.com/this%24*%28%29*%23.txt&fileName=this%24*%28%29*%23.txt;
    String encodeUrl = url.replace(fileName, URLEncoder.encode(fileName, "UTF-8"));
    // 解码
    String decodeUrl = URLDecoder.decode(url, "UTF-8");
    System.out.println(encodeUrl + "; " + decodeUrl);
}

2.2 URL 解码

编码和解码的过程是可逆的

String name = "23432424";
String encodeStr = URLEncoder.encode(name, "utf-8");
String decode = URLDecoder.decode(encodeStr, "utf-8");
上一篇 下一篇

猜你喜欢

热点阅读