gpt4 book ai didi

java - sun.net.httpserver 写入流的字节太多

转载 作者:搜寻专家 更新时间:2023-10-31 19:53:44 24 4
gpt4 key购买 nike

我使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com