解析URL中的攜帶的參數到Map


手動解析URL字符串中的參數,寫了一個工具類。

 1     final int MIN_ARRAY_LEN = 2;
 2     final int DIVIDE_INTO_PAIRS = 2;
 3 
 4     public Map<String, String> parseRequestParam(String url) {
 5         Map<String, String> map = new HashMap<String, String>();
 6         if (!url.contains("?")) {
 7             return null;
 8         }
 9         String[] parts = url.split("\\?", DIVIDE_INTO_PAIRS);
10         if (parts.length < MIN_ARRAY_LEN) {
11             return null;
12         }
13         String parsedStr = parts[1];
14         if (parsedStr.contains("&")) {
15             String[] multiParamObj = parsedStr.split("&");
16             for (String obj : multiParamObj) {
17                 parseBasicParam(map, obj);
18             }
19             return map;
20         }
21         parseBasicParam(map, parsedStr);
22         return map;
23 
24     }
25 
26     private void parseBasicParam(Map<String, String> map, String str) {
27         String[] paramObj = str.split("=");
28         if (paramObj.length < MIN_ARRAY_LEN) {
29             return;
30         }
31         map.put(paramObj[0], paramObj[1]);
32     }

感覺不是很完善,期待有更好的改進意見。


免責聲明!

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



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