URLDecoder.decode(String str,String charSet)的大致實現原理
阿新 • • 發佈:2019-02-14
URL編碼 百分號編碼 URLDecoder.decode的大致實現原理
Java程式碼- 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
- 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
- // 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>