0

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?

Dan
  • 3,647
  • 5
  • 20
  • 26
  • Isn't this a very old class? why do you use it? – Just another Java programmer May 27 '22 at 14:16
  • That means that you've already sent response to a user in the moment of calling sendResponseHeaders – Bane2000 May 27 '22 at 14:26
  • 1
    Ugh, that code is not well written. Please use braces for all code blocks in `if` and `else`. If you're going to `close` anyway then you don't need `flush`. You don't need to assign `null` to `os` if you're going to always set it, i.e. in both branches of the `if / else` statement. However, your issue is that you call `getResponseBody` before `sendResponseHeaders` in the `else` part of the first `if`, [which is explicitly forbidden](https://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#sendResponseHeaders-int-long-). – Maarten Bodewes May 27 '22 at 14:52

0 Answers0