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();
}
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<String, String> queryToMap(String query) {
Map<String, String> 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<String, String> params = queryToMap(httpExchange.getRequestURI().getQuery());
System.out.println("param A=" + params.get("A"));
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<String, String> parseQueryString(String qs) {
Map<String, String> 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;
}
Building on the answer by @anon01, this is how to do it in Groovy:
Map<String,String> 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']