請求參數中的"+"號為什么會丟失,如何保證參數完整


最近在開發中碰見一個問題,后端代碼調用接口,在請求端參數沒有任何問題,但是當接口接收到參數時,其中的加號全部變為了空格。

在查閱資料后發現是URLDecoder方法的問題,以下是URLDecoder的文檔說明:

The following rules are applied in the conversion:

  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same.
  • The special characters ".", "-", "*", and "_" remain the same.
  • The plus sign "+" is converted into a space character "   " .
  • A sequence of the form "%xy" will be treated as representing a byte where xy is the two-digit hexadecimal representation of the 8 bits. Then, all substrings that contain one or more of these byte sequences consecutively will be replaced by the character(s) whose encoding would result in those consecutive bytes. The encoding scheme used to decode these characters may be specified, or if unspecified, the default encoding of the platform will be used

文檔中很明顯,URLDecoder會將加號轉變為空格,其他的符號".", "-", "*", "_"將保持不變。

Spring mvc框架在給參數賦值的時候調用了URLDecoder,那要解決這個問題,需要在請求的時候對"+"做處理:

String plusEncode = URLEncoder.encode("+", "UTF-8");
param = param.replaceAll("\\+", plusEncode);

這里在請求發送前,將加號用URLEcoder進行編碼,並將參數json中的所有加號替換成編碼后的字符。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM