Home » Java » sun.net.httpserver too many bytes to write to stream

sun.net.httpserver too many bytes to write to stream

Posted by: admin December 28, 2021 Leave a comment

Questions:

I wrote my own little http server using com.sun.net.httpserver.HttpServer

public void handle(HttpExchange t) throws IOException {
    OutputStream os = t.getResponseBody();
    os.write(generateResponse(t).getBytes());
    os.close();
}

If I try to write to the output stream and my response is larger then 1024 I get the following exception:

java.io.IOException: insufficient bytes written to stream
        at sun.net.httpserver.FixedLengthOutputStream.close(FixedLengthOutputStream.java:89)
        at sun.net.httpserver.PlaceholderOutputStream.close(ExchangeImpl.java:454)
        at MyHttpServer$MyHandler.handle(MyHttpServer.java:49)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
        at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:80)
        at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:675)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77)
        at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:647)
        at sun.net.httpserver.ServerImpl$DefaultExecutor.execute(ServerImpl.java:158)
        at sun.net.httpserver.ServerImpl$Dispatcher.handle(ServerImpl.java:431)
        at sun.net.httpserver.ServerImpl$Dispatcher.run(ServerImpl.java:396)
        at java.lang.Thread.run(Thread.java:745)
Answers:

This worked for me.

try {
    byte[] bs = responseString.getBytes("UTF-8");
    httpExchange.sendResponseHeaders(200, bs.length);
    OutputStream os = httpExchange.getResponseBody();
    os.write(bs);
} catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

###

This is how I solved it:

httpExchange.sendResponseHeaders(200, 0);
try (BufferedOutputStream out = new BufferedOutputStream(httpExchange.getResponseBody())) {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
        byte [] buffer = new byte [BUFFER_SIZE];
        int count ;
        while ((count = bis.read(buffer)) != -1) {
            out.write(buffer, 0, count);
        }
        out.close();
    }
}