Java实现中文转成url编码

1. 整体流程

flowchart TD
    A(输入中文字符串) --> B(将中文字符串转成字节数组)
    B --> C(遍历字节数组)
    C --> D(将每个字节转成十六进制)
    D --> E(拼接每个字节的十六进制)
    E --> F(添加%前缀)
    F --> G(输出URL编码后的字符串)

2. 具体步骤

步骤1:将中文字符串转成字节数组

// 将中文字符串转成字节数组
byte[] bytes = input.getBytes("UTF-8");

步骤2:遍历字节数组

// 遍历字节数组
for (byte b : bytes) {
    // 实现代码
}

步骤3:将每个字节转成十六进制

// 将每个字节转成十六进制
String hex = Integer.toHexString(b & 0xFF);

步骤4:拼接每个字节的十六进制

// 拼接每个字节的十六进制
if (hex.length() == 1) {
    hex = '0' + hex;
}

步骤5:添加%前缀

// 添加%前缀
result.append('%').append(hex);

步骤6:输出URL编码后的字符串

// 输出URL编码后的字符串
String output = result.toString();

3. 代码示例

public class URLEncoder {
    public static void main(String[] args) {
        String input = "你好";
        try {
            // 将中文字符串转成字节数组
            byte[] bytes = input.getBytes("UTF-8");
            
            // 遍历字节数组
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                // 将每个字节转成十六进制
                String hex = Integer.toHexString(b & 0xFF);
                
                // 拼接每个字节的十六进制
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                
                // 添加%前缀
                result.append('%').append(hex);
            }
            
            // 输出URL编码后的字符串
            String output = result.toString();
            System.out.println(output); // 输出:%E4%BD%A0%E5%A5%BD
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

4. 类图

classDiagram
    URLEncoder --|> Object
    Object <|-- String

通过以上步骤和示例代码,你可以实现将中文字符串转成URL编码的功能。希望对你有所帮助!