简体   繁体   中英

Unable to respond to HEAD requests in Java

I am writing a personal web server. When I send the GET request to the system, the system responds well. But when I send the HEAD request, I get the following problems:

sun.net.httpserver.ExchangeImpl sendResponseHeaders WARNING: sendResponseHeaders: being invoked with a content length for a HEAD request java.io.IOException: response headers not sent yet at jdk.httpserver/sun.net.httpserver.PlaceholderOutputStream.checkWrap(ExchangeImpl.java:448) at jdk.httpserver/sun.net.httpserver.PlaceholderOutputStream.write(ExchangeImpl.java:458) at ir.utux.service.HandleHttpResponse.writeResponse(HandleHttpResponse.java:32)

This is the code I wrote to manage the response, to simplify HEAD and GET together.

public void writeResponse(SettingModal settingModal) {
    try {
        switch (requestHeader.getMethod()) {
            case HEAD,GET -> {
                response.getResponseHeaders().set("Server", "utux HttpServer");
                response.getResponseHeaders().set("Connection", "close");
                response.getResponseHeaders().set("Transfer-encoding", "chunked");
                response.getResponseHeaders().set("Content-Type", ContentType.HTML);
                response.sendResponseHeaders(HttpStatus.SC_OK, "".length());
                response.getResponseBody().write("".getBytes(StandardCharsets.UTF_8));
                response.getResponseBody().flush();
                response.getResponseBody().close();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我发现问题 BODY 不应响应 HEAD 请求而发送。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM