關於url中特殊字符不得不說的事

在向後臺傳參時,很多時候都會拼在url後面,這就免不了會產生很多問題。
當參數是中文時,都知道轉碼( encodeURI() )、解碼( java.net.URLDecoder.decode() ),以此解決中文無法傳輸的問題。
但當都是英文的時候就沒必要了,因此也常常會忽略掉英文中的符號,所以會出現一些突如其來的bug:
balabala一大串,意思就是對不起,這個字符我不認識,搞不了。

信息: Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
	at org.apache.coyote.http11.InternalAprInputBuffer.parseRequestLine(InternalAprInputBuffer.java:238)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1028)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
	at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2555)
	at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2544)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)

然後我就去查了一下RFC7230和RFC3986到底是個啥玩意兒,然後發現RFC3986(RFC7230是RFC3986的補充完善)中的一下規定:
1、reserved    = gen-delims / sub-delims
gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
翻過來就是:保留字符包含gen-decimal和sub-decimal,gen-delims包含 /?#{}@ 7個,sub-decimal包含 !$&'()*+,;= 11個。
2、Characters that are allowed in a URI but do not have a reserved purpose are called unreserved.These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.
unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
翻過來就是:URI中允許但沒有保留的字符,被稱爲無保留。這些包括大寫和小寫字母(a-zA-Z),十進制數字(0-9),連字符,句點,下劃線和波形符號(- _ . ~) 

不安全字符是指那些在URL中沒有特殊含義,但在URL所在的上下文中可能具有特殊意義的字符 空格、引號、< > # % { } | \ ^ [ ] ` ~ 其中的這些不安全字符一般都需要編碼

然後,我就把所有的字符都測了一下,又發現+通過url到了後臺居然不見了,變成了空格,emmmm,轉碼吧,得用encodeURIComponent()。

既然這樣那不安全字符也這麼來一遍就沒問題了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章