转载

使用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)

  1. Exception in thread "main" java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u9"
  2. at java.net.URLDecoder.decode(URLDecoder.java:194)
  3. at com.hbzx.controller.PayResultController.main(PayResultController.java:253

Java调用 URLDecoder.decode(str, "UTF-8"); 抛出以上的异常,其主要原因是% 在URL中是特殊字符,需要特殊转义一下,

解决办法:使用%25替换字符串中的%号

  1. url = url.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
  2. String urlStr = URLDecoder.decode(url, "UTF-8");

摘自:https://blog.csdn.net/afgasdg/article/details/40304817
            https://blog.csdn.net/jackpk/article/details/5494156
正文到此结束
Loading...