我使用com.sun.net.httpserver.HttpServer
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)
答案 0 :(得分:3)
这就是我解决它的方法:
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);
}
}
}