lahiru lakruwan
lahiru lakruwan

Reputation: 1

How to fix java.io.IOException: headers already sent error?

I'm implementing a web server using sun.net.HttpServer to enable send response message to the user. But sometimes I am getting the error message below.

java.io.IOException: headers already sent at sun.net.httpserver.ExchangeImpl.sendResponseHeaders(ExchangeImpl.java:204) at sun.net.httpserver.HttpExchangeImpl.sendResponseHeaders(HttpExchangeImpl.java:86)

Here is coding

public static void sendResponse(HttpExchange httpExchange, int httpCode, String res) throws Exception {
        
        OutputStream os = null;

        if (res != null) {
            
            httpExchange.getResponseHeaders().add("Content-Type", "application/json"); 
            httpExchange.sendResponseHeaders(httpCode, res.getBytes().length);
            os = httpExchange.getResponseBody();
            os.write(res.getBytes());
            os.flush();
        } else {
            os = httpExchange.getResponseBody();
            httpExchange.sendResponseHeaders(httpCode, 0);
            os.flush();
        }
        if (os != null) os.close(); os = null;
        if (httpExchange != null) httpExchange.close();httpExchange = null;
        res = null;
        
    }

Is it a memory-cache issue? And how to fix it?

Upvotes: 0

Views: 416

Answers (0)

Related Questions