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) {
- e1.printStackTrace();
- }
- }
- public static void main(String[] args) {
- new testURLEncode().testURLEncode();
- new testURLEncode().testURLEncodeGBK();
- }
- }
-
url后参数的转码与解码
import java.net.URLDecoder;
import java.net.URLEncoder;String strTest = "?=abc?中%1&2<3,4>";
strTest = URLEncoder.encode(strTest, "UTF-8");
System.out.println(strTest);
strTest = URLDecoder.decode(strTest,"UTF-8");
System.out.println(strTest);
执行结果:
%3F%3Dabc%3F%E4%B8%AD%251%262%3C3%2C4%3E
?=abc?中%1&2<3,4>