簡體   English   中英

java httpserver處理POST請求並讀取html表單信息

[英]java httpserver handling POST requests and read the html form information

我試圖用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控制台中顯示表單信息,所以我該怎么做? 所以請你幫幫我

我沒有測試它,因為我沒有准備發送POST消息的表單,或者不知道如何從頭開始創建HTTP POST消息。

您可以使用String類將已讀取的數據打印到控制台:

System.out.print(new String(data));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM