如何使用Java HttpServer/HttpExchange获取GET中的查询字符串?
2022-09-01 14:00:25
我试图在Java中创建一个简单的HttpServer来处理GET请求,但是当我尝试获取请求的GET参数时,我注意到HttpExchange类没有这方面的方法。
有没有人知道一种简单的方法来读取GET参数(查询字符串)?
这是我的处理程序的样子:
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();
}
}
..和主要方法:
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();
}