How to read parameters and value from query string using java

I use Ciui from google code, and all requests are just GET requests, not POST. Calls are made by ajax (I'm not sure). I need to know how to read the "searchstring" parameter from this url. When I read this in my servlet using the getQueryString () method, I cannot correctly form the actual text. This unicode (when% is replaced with /), as the text, is actually in Chinese. Please give me how to decode the search string and create the string.

http://xxxx.com?searchString=%u8BF7%u5728%u6B64%u5904%u8F93%u5165%u4EA7%u54C1%u7F16%u53F7%u6216%u540D%u79F0&button=%E6%90%9C%E7%B4%A2

Another parameter has the correct percentage encoding, which I can decode using URL decoding. thanks in advance

+3
source share
4 answers

Your encoding scheme for these Chinese characters actually violates web standards (namely RFC 3986 ): the percent sign is a reserved character that can be used, except for the standard percentage encoding.

( UTF-8 ); getParameter(). , .

+2

, , :

    public static Map<String, String> getQueryMap(String query)  
{  
    String[] params = query.split("&");  
    Map<String, String> map = new HashMap<String, String>();  
    for (String param : params)  
    {  String [] p=param.split("=");
        String name = p[0];  
      if(p.length>1)  {String value = p[1];  
        map.put(name, value);
      }  
    }  
    return map;  
} 

, :

 Map params=getQueryMap(querystring);
 String id=(String)params.get("id");
 String anotherparam=(String)params.get("anotherparam");
+6
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String searchString = request.getParameter("searchString");
    // process searchString
}

.

+1

Java 8.

/:

List<AbstractMap.SimpleEntry<String, String>> list = 
        asList(queryString.split("&")).stream()
        .map(s -> copyOf(s.split("="), 2))
        .map(o -> new AbstractMap.SimpleEntry<String, String>(o[0], o[1]) )
        .collect(toList());

@Tuno , ( ) groupingBy:

Map<String, List<String>> llist = 
       asList(queryString.split("&")).stream()
       .map(s -> copyOf(s.split("="), 2))
       .collect(groupingBy(s -> s[0], mapping(s -> s[1], toList())));

I suggest decoding values ​​using URLDecoder.decode(String s, String enc)

Both solutions print the contents of the collection using this line:

list.stream().forEach(s -> System.out.println(s.getKey() + " = " + s.getValue()));
+1
source

All Articles