如何使用 Java HttpServer/HttpExchange 在 GET 中获取查询字符串?

新手上路,请多包涵

我正在尝试用 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();
}

原文由 Tibor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

以下: httpExchange.getRequestURI().getQuery()

将返回类似于以下格式的字符串: "field1=value1&field2=value2&field3=value3..."

所以你可以简单地自己解析字符串,这就是解析函数的样子:

 public Map<String, String> queryToMap(String query) {
    if(query == null) {
        return null;
    }
    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;
}

这就是您可以使用它的方式:

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

原文由 anon01 发布,翻译遵循 CC BY-SA 4.0 许可协议

这个答案与 annon01 的相反,正确地解码了键和值。它不使用 String.split ,而是使用 indexOf 扫描字符串,速度更快。

 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;
}

原文由 Oliv 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题