URL請求中文、符號“亂碼”(解碼、轉碼)解決方式
阿新 • • 發佈:2018-11-22
有的字元在url中傳遞的時候回編碼(可能是自動的)將其符號轉變為%加上ASCII碼;如果在客戶端或者服務端接收到的時候沒有解碼就會出現類似亂碼的問題;其實不然只是沒有進行解碼
附部分編碼規則
十六進位制值 | |||
1. | + | URL 中+號表示空格 | %2B |
2. | 空格 | URL中的空格可以用+號或者編碼 | %20 |
3. | / | 分隔目錄和子目錄 | %2F |
4. | ? | 分隔實際的 URL 和引數 | %3F |
5. | % | 指定特殊字元 | %25 |
6. | # | 表示書籤 | %23 |
7. | & | URL 中指定的引數間的分隔符 | %26 |
8. | = | URL 中指定引數的值 | %3D |
這種情況就需要解碼了,解決方式如下
java中的轉碼,這裡需要自己對str也就是url的字串進行下非空判斷如果為空的話返回個空字串
private final static String ENCODE = "UTF-8"; //自己的編碼格式
public static String getURLEncoderString(String str) { String result = ""; if (null == str) { return ""; } try { result = java.net.URLEncoder.encode(str, ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
java中的解碼
public static String getURLDecoderString(String str) { String result = ""; if (null == str) { return ""; } try { result = java.net.URLDecoder.decode(str, ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
javastript中的轉碼
escape(String s)
javastript中的解碼
unescape(String s)