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

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

    Building on the answer by @anon01, this is how to do it in Groovy:

    Map getQueryParameters( HttpExchange httpExchange )
    {
        def query = httpExchange.getRequestURI().getQuery()
        return query.split( '&' )
                .collectEntries {
            String[] pair = it.split( '=' )
            if (pair.length > 1)
            {
                return [(pair[0]): pair[1]]
            }
            else
            {
                return [(pair[0]): ""]
            }
        }
    }
    

    And this is how to use it:

    def queryParameters = getQueryParameters( httpExchange )
    def parameterA = queryParameters['A']
    

提交回复
热议问题