关于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()。

既然这样那不安全字符也这么来一遍就没问题了。

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