java httpserver处理POST请求并读取html表单信息

时间:2016-03-14 09:31:03

标签: java http post httpserver

我正在尝试在java中编写一个可以处理&的简单HTTP服务器。读取来自html表单的POST请求

public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); 
server.start();
}
 static class MyHandler implements HttpHandler {

   @Override
    public void handle(HttpExchange he) throws IOException {
     system.out.println("Serving the request");

     if (he.getRequestMethod().equalsIgnoreCase("POST")) {
  try {
     Headers requestHeaders = he.getRequestHeaders();
     Set<Map.Entry<String, List<String>>> entries = requestHeaders.entrySet();

     int contentLength = Integer.parseInt(requestHeaders.getFirst("Content-length"));
     System.out.println(""+requestHeaders.getFirst("Content-length"));

     InputStream is = he.getRequestBody();

     byte[] data = new byte[contentLength];
     int length = is.read(data);

     Headers responseHeaders = he.getResponseHeaders();

     he.sendResponseHeaders(HttpURLConnection.HTTP_OK, contentLength);

     OutputStream os = he.getResponseBody();

     os.write(data);
     he.close();

     } catch (NumberFormatException | IOException e) {
     }
     }

    }
    }
    }

上面的代码从html表单中读取发布数据,并在浏览器窗口中输出 但我想在java控制台中显示表单信息,那我该怎么做呢?所以请帮助我。

0 个答案:

没有答案