Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove Content-length header from HTTP response generated in a simple server?

Following is my sample HTTP server. I need to remove the 'Content-length:' header generated at the response. I have tried many approaches and not succeded. Is there any way to remove the content-length from server response?

public class SimpleHttpServer {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(9000), 0);
        server.createContext("/test", new TestHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class TestHandler implements HttpHandler {
        public void handle(HttpExchange t) throws IOException {
            byte[] response = "Welcome to Test Server..!!\n".getBytes();
            t.sendResponseHeaders(200, response.length);
            OutputStream os = t.getResponseBody();
            os.write(response);
            os.close();
        }
    }
}
like image 504
Methma Avatar asked Feb 18 '26 02:02

Methma


1 Answers

A workaround could be:

t.sendResponseHeaders(200, 0);

Note that

If the response length parameter is 0, then chunked transfer encoding is used and an arbitrary amount of data may be sent.

like image 140
Andrew Tobilko Avatar answered Feb 20 '26 14:02

Andrew Tobilko