How to obtain the query string in a GET with Java HttpServer/HttpExchange?

前端 未结 4 1271
孤独总比滥情好
孤独总比滥情好 2021-02-05 06:27

I am trying to create a simple HttpServer in Java to handle GET requests, but when I try to get the GET parameters for a request I noticed the HttpExchange class does not have a

4条回答
  •  滥情空心
    2021-02-05 06:48

    This answer, contrary to annon01's, properly decodes the keys and values. It does not use String.split, but scans the string using indexOf, which is faster.

    public static Map parseQueryString(String qs) {
        Map result = new HashMap<>();
        if (qs == null)
            return result;
    
        int last = 0, next, l = qs.length();
        while (last < l) {
            next = qs.indexOf('&', last);
            if (next == -1)
                next = l;
    
            if (next > last) {
                int eqPos = qs.indexOf('=', last);
                try {
                    if (eqPos < 0 || eqPos > next)
                        result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), "");
                    else
                        result.put(URLDecoder.decode(qs.substring(last, eqPos), "utf-8"), URLDecoder.decode(qs.substring(eqPos + 1, next), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e); // will never happen, utf-8 support is mandatory for java
                }
            }
            last = next + 1;
        }
        return result;
    }
    

提交回复
热议问题