我使用com.sun.net.httpserver.HttpServer编写了自己的小型http服务器

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

如果我尝试写入输出流并且响应较大,则1024会出现以下异常:
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)

最佳答案

这对我有用。

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);
}

关于java - sun.net.httpserver太多字节无法写入流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33695620/

10-14 12:20