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

前端 未结 4 1270
孤独总比滥情好
孤独总比滥情好 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:51

    The following: httpExchange.getRequestURI().getQuery()

    will return string in format similar to this: "field1=value1&field2=value2&field3=value3..."

    so you could simply parse string yourself, this is how function for parsing could look like:

    public Map queryToMap(String query) {
        Map result = new HashMap<>();
        for (String param : query.split("&")) {
            String[] entry = param.split("=");
            if (entry.length > 1) {
                result.put(entry[0], entry[1]);
            }else{
                result.put(entry[0], "");
            }
        }
        return result;
    }
    

    And this is how you could use it:

    Map params = queryToMap(httpExchange.getRequestURI().getQuery()); 
    System.out.println("param A=" + params.get("A"));
    

提交回复
热议问题