Two methods of encoding and decoding URLs in Java

1. Use java.net.URLEncoder and java.net.URLDecoder classes

public class UrlEncoder {
    
    

    public static void main(String[] args) {
    
    
        try {
    
    
            String url = "https://www.baidu.com/sugrec?&prod=pc_his&from=pc_web&_t=1680167620430&req=2&csor=0";
            String encodedUrl = java.net.URLEncoder.encode(url, "UTF-8");
            System.out.println("加密后:" + encodedUrl);
            String decodedUrl = java.net.URLDecoder.decode(encodedUrl, "UTF-8");
            System.out.println("解密后:" + decodedUrl);
            /**
             * 输出:
             * 加密后:https%3A%2F%2Fwww.baidu.com%2Fsugrec%3F%26prod%3Dpc_his%26from%3Dpc_web%26_t%3D1680167620430%26req%3D2%26csor%3D0
             * 解密后:https://www.baidu.com/sugrec?&prod=pc_his&from=pc_web&_t=1680167620430&req=2&csor=0
             */
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

    }

}

In the above code, use the URLEncoder.encode method to encode the URL, specify the encoding method as UTF-8, and generate the encoded URL string. Use the URLDecoder.decode method to decode the encoded URL string, specify the decoding method as UTF-8, and generate the decoded URL string.

2. Use java.nio.charset.StandardCharsets and java.util.Base64 classes

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

public class UrlEncoder {
    
    

    public static void main(String[] args) {
    
    
        try {
    
    
            String url = "https://www.baidu.com/sugrec?&prod=pc_his&from=pc_web&_t=1680167620430&req=2&csor=0";
            String encodedUrl = Base64.getEncoder().encodeToString(url.getBytes(StandardCharsets.UTF_8));
            System.out.println("加密后:" + encodedUrl);
            String decodedUrl = new String(Base64.getDecoder().decode(encodedUrl), StandardCharsets.UTF_8);
            System.out.println("解密后:" + decodedUrl);
            /**
             * 输出:
             * 加密后:aHR0cHM6Ly93d3cuYmFpZHUuY29tL3N1Z3JlYz8mcHJvZD1wY19oaXMmZnJvbT1wY193ZWImX3Q9MTY4MDE2NzYyMDQzMCZyZXE9MiZjc29yPTA=
             * 解密后:https://www.baidu.com/sugrec?&prod=pc_his&from=pc_web&_t=1680167620430&req=2&csor=0
             */
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

    }

}

In the above code, use the Base64.getEncoder().encodeToString method to convert the URL string into a UTF-8 encoded byte array and perform Base64 encoding. Use the new String(Base64.getDecoder().decode(encodedUrl), StandardCharsets.UTF_8) method to decode the encoded URL string to generate a decoded URL string.

It should be noted that a character set needs to be specified when encoding and decoding URLs. Commonly used character sets include UTF-8, ISO-8859-1, and so on. When using URLs for network transmission, it is generally recommended to use UTF-8 encoding.

おすすめ

転載: blog.csdn.net/weixin_43749805/article/details/129857624