URL编码 百分号编码 URLDecoder.decode的大致实现原理

本文通过实例演示了URL编码(百分号编码)的过程及其解码原理。主要使用Java的URLEncoder和URLDecoder类来实现字符串的编码与解码,并展示了不同字符集(如utf-8与GBK)对编码结果的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

URL编码 百分号编码 URLDecoder.decode的大致实现原理

package com.dt.test;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/***
 * URL编码又叫百分号编码 URLDecoder.decode的大致实现原理
 */
class testURLEncode {
	public void testURLEncode() {
		String testString;
		try {
			testString = URLEncoder.encode("中文", "utf-8");
			System.out.println("testString : " + testString);
			testString = testString.replace("%", "");
			int length = testString.length() / 2;
			byte[] data = new byte[length];
			for (int i = 0; i < length; i++) {
				data[i] = (byte) Integer.parseInt(testString.substring(2 * i,
						2 * i + 2), 16);
			}
			String result = new String(data, "utf-8");
			System.out.println("result : " + result);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	public void testURLEncodeGBK() {
		String testString;
		String testString0;
		
		try {
			testString = URLEncoder.encode("中文", "utf-8");
			testString0 = testString;
			System.out.println("testString : " + testString);
			
			testString =  URLDecoder.decode(testString0,"GBK");
			System.out.println("decode : " + testString);
			
			testString =  URLDecoder.decode(testString0,"utf-8");
			System.out.println("decode : " + testString);
			testString =  URLEncoder.encode("中文", "GBK");
			System.out.println("decode : " + testString);
			testString =  URLDecoder.decode(testString,"GBK");
			System.out.println("decode : " + testString);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public static void main(String[] args) {

		new testURLEncode().testURLEncode();
		new testURLEncode().testURLEncodeGBK();
	}
}

 

testString : %E4%B8%AD%E6%96%87
result : 中文
testString : %E4%B8%AD%E6%96%87
decode : 涓枃
decode : 中文
decode : %D6%D0%CE%C4
decode : 中文

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值