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

Viewed 36418

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 method for that.

Does anybody know an easy way to read the GET parameters (query string)?

This is how my handler looks like:

public class TestHandler{
  @Override
  public void handle(HttpExchange exc) throws IOxception {
    String response = "This is the reponse";
    exc.sendResponseHeaders(200, response.length());

    // need GET params here

    OutputStream os = exc.getResponseBody();
    os.write(response.getBytes());
    os.close();
  } 
}

.. and the main method:

public static void main(String[] args) throws Exception{
  // create server on port 8000
  InetSocketAddress address = new InetSocketAddress(8000);
  HttpServer server = new HttpServer.create(address, 0);

  // bind handler
  server.createContext("/highscore", new TestHandler());
  server.setExecutor(null);
  server.start();
}
5 Answers

Stumbled across this, and figured I'd toss a Java 8 / Streams implementation out here, whilst adding a few extra bits (not in previous answers).

Extra 1: I've added a filter to avoid processing any empty params. Something that should not happen, but it allows a cleaner implementation vs. not handling the issue (and sending an empty response). An example of this would look like ?param1=value1&param2=

Extra 2: I've leveraged String.split(String regex, int limit) for the second split operation. This allows a query parameter such as ?param1=it_has=in-it&other=something to be passed.

public static Map<String, String> getParamMap(String query) {
    // query is null if not provided (e.g. localhost/path )
    // query is empty if '?' is supplied (e.g. localhost/path? )
    if (query == null || query.isEmpty()) return Collections.emptyMap();

    return Stream.of(query.split("&"))
            .filter(s -> !s.isEmpty())
            .map(kv -> kv.split("=", 2)) 
            .collect(Collectors.toMap(x -> x[0], x-> x[1]));

}

Imports

import java.util.Map;
import java.util.Collections;
import java.util.stream.Stream;
import java.util.stream.Collectors;

If, like me, your query string allows the same name to occur multiple times, the you'll want the values to be lists (like in Netty's QueryStringDecoder). Adapted from the best answer here..

  final static Charset UTF_8 = Charset.forName("UTF-8");

  static Map<String, List<String>> queryMap(HttpExchange exchange) {
    return queryMap(exchange.getRequestURI().getRawQuery());
  }
  
  static Map<String, List<String>> queryMap(String query) {
    if (query == null || query.isEmpty()) {
      return Map.of();
    }
    Map<String, List<String>> result = new HashMap<>();
    for (String param : query.split("&")) {
      String[] entry = param.split("=");
      var name = entry[0];
      var list = result.get(name);
      if (list == null) {
        list = new ArrayList<>(2);
        result.put(name, list);
      }
      String value = entry.length > 1 ?
            URLDecoder.decode(entry[1], UTF_8) : "";
      
      list.add(value);
    }
    return result;
  }
Related