使用URLEncoder、URLDecoder進行URL參數的轉碼與解碼


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>

jdk相關說明:

String java.net.URLEncoder.encode(String s, String enc) throws UnsupportedEncodingException

Translates a string into 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.

Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilites.

Parameters:
    s String to be translated. 
    enc The name of a supported character encoding. 
Returns:
    the translated String. 
Throws:
    UnsupportedEncodingException - If the named encoding is not supported 
Since:
    1.4 
See Also:
    URLDecoder.decode(java.lang.String, java.lang.String)

 
String java.net.URLDecoder.decode(String s, String enc) throws UnsupportedEncodingException

Decodes a 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 "%xy".

Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilites.

Parameters:
    s the String to decode 
    enc The name of a supported character encoding. 
Returns:
    the newly decoded String 
Throws:
    UnsupportedEncodingException - If character encoding needs to be consulted, but named character encoding is not supported 
Since:
    1.4 
See Also:
    URLEncoder.encode(java.lang.String, java.lang.String)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM