Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

http

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)
like image 926
javapenguin Avatar asked Nov 13 '15 14:11

javapenguin


2 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);
}
like image 96
Pankaj Kumar Avatar answered Nov 18 '22 10:11

Pankaj Kumar


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();
    }
}
like image 43
user2778037 Avatar answered Nov 18 '22 11:11

user2778037