1. 程式人生 > 其它 >Http GET 請求引數中文亂碼

Http GET 請求引數中文亂碼

兩種解決方式

第1種:程式碼裡轉換

String name = request.getParamter("name");
String nameUtf8 = new String(name.getBytes("ISO8859-1"), "UTF-8");

第2種:修改Tomcat配置

TOMCAT_HOME/conf/server.xml

....
<!-- 修改前 -->
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

<!-- 修改後 -->
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
           	   URIEncoding="UFT-8"/>

注意:

百度到的結果一般都是上面這兩種解決方法。

第一種方法太麻煩了,get請求裡有十幾個引數,難道都要一個一個的 new String(name.getBytes("ISO8859-1"), "UTF-8"); 嗎?這樣的程式碼笨重,且修改時不小心就會出錯。

第二種方法很好,但要注意:tomcat7 及以上版本預設都設定了 URIEncoding="UFT-8",不必再去手動設定。這一點,百度到的部落格裡一個說的都沒有,全都是互相轉載,不知多少年前的了。最好的辦法就是看官方文件。

我本地和測試環境下get請求引數值中文都是正常的,一到生產就亂碼了,查不到資料。花了兩個多小時後才確定是開發和生產環境不同導致的

檢視當前tomcat版本

# 進入 TOMCAT_HOME/bin,執行 version.sh 檢視當前tomcat版本
[root@jtdev bin]# sh version.sh 
/opt/tomcat9/logs/catalina.out
Using CATALINA_BASE:   /opt/tomcat9
Using CATALINA_HOME:   /opt/tomcat9
Using CATALINA_TMPDIR: /opt/tomcat9/temp
Using JRE_HOME:        /usr/java8/jdk1.8.0_11/jre
Using CLASSPATH:       /opt/tomcat9/bin/bootstrap.jar:/opt/tomcat9/bin/tomcat-juli.jar
Server version: Apache Tomcat/9.0.35
Server built:   May 5 2020 20:36:20 UTC
Server number:  9.0.35.0
OS Name:        Linux
OS Version:     2.6.32-504.el6.x86_64
Architecture:   amd64
JVM Version:    1.8.0_11-b12
JVM Vendor:     Oracle Corporation

檢視官方文件

TOMCAT_HOME/webapps/docs 目錄下儲存的就是當前版本的文件,當啟動tomcat後,訪問 http://host:port/docs 即可

  1. 選擇左側Referance選單欄下的 Configuration,進入配置項說明頁面
  2. 再選擇左側Connectors選單欄下的 HTTP/1.X ,進入Connector元素配置項說明
  3. 全域性搜尋 URIEncoding
URIEncoding This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. The default value is UTF-8.