1. 程式人生 > >關於UrlEncoder和UrlDecode

關於UrlEncoder和UrlDecode

關於 UrlEncoder和UrlDecode這兩個的含義,主要是針對web專案中url的加碼和解碼功能

先寫個例子

		try {
			String str1 = "?=abdddc?周杰倫%4&9<9,2>";
			String strEncode = URLEncoder.encode(str1, "utf-8");
			System.out.println("編碼之後:"+strEncode);
			
			String str2 = "%3F%3Dabdddc%3F%E5%91%A8%E6%9D%B0%E4%BC%A6%254%269%3C9%2C2%3E";
			String strDecode = URLDecoder.decode(str2, "utf-8");
			System.out.println("解碼之後:"+strDecode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

輸出結果:

編碼之後:%3F%3Dabdddc%3F%E5%91%A8%E6%9D%B0%E4%BC%A6%254%269%3C9%2C2%3E
解碼之後:?=abdddc?周杰倫%4&9<9,2>

我們進入到程式碼裡面

URLDecoder.decode

public static String decode(String s, String enc){...}

可以看到該介面的描述部分如下:

    /**
     * Decodes a {@code application/x-www-form-urlencoded} string using a specific
     * encoding scheme.
     * The supplied encoding is used to determine
     * what characters are represented by any consecutive sequences of the
     * form "<i>{@code %xy}</i>".
     */ 

Decodes a {@code application/x-www-form-urlencoded} string using a specific encoding scheme 

將application/x-www-form-urlencoded 格式的url地址資訊使用指定的編碼格式進行解碼

The supplied encoding is used to determine what characters are represented by any consecutive sequences of the  form

我們根據提供的字元編碼格式來決定將任何url資訊解碼成對應要呈現的字串

URLEncoder.encode

public static String encode(String s, String enc)

可以看到該介面的描述部分如下:

    /**
     * Translates a string into {@code application/x-www-form-urlencoded}
     * format using a specific encoding scheme. This method uses the
     * supplied encoding scheme to obtain the bytes for unsafe
     * characters.

    */

Translates a string into {@code application/x-www-form-urlencoded} format using a specific encoding scheme.

通過給定的編碼格式將字串資訊加碼成我們需要的格式型別。比如:application/x-www-form-urlencoded

 This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.

這個方法使用給定的字串編碼來進行加碼,為這些不安全的字串獲取對應的二進位制位元組碼

翻譯或者有錯誤地方,歡迎批評改正。