gpt4 book ai didi

java - 尝试写入文件时出现 Broken Pipe 异常

转载 作者:行者123 更新时间:2023-12-01 05:14:57 26 4
gpt4 key购买 nike

我正在尝试编写一个非常简单的应用程序,它将使用 PUT 请求通过 HTTP 将视频上传到我的一台服务器。我的代码如下所示:

socket = new Socket();
socket.connect(new InetSocketAddress(ticket.getHost(), 80));

outputStream = socket.getOutputStream();

// begin forming the request
outputStream.write(("PUT " + ticket.getEndpoint() + " HTTP/1.1\r\n" +
"Host: " + ticket.getHost() + "\r\n" +
"Content-Length: " + getStreamFile().length() + "\r\n" +
"Content-Type: video/mp4\r\n\r\n").getBytes());

// now, let's write us some binary data
fileInputStream = new FileInputStream(getStreamFile());
inputStream = new BufferedInputStream(fileInputStream);

byte[] fileBytes = new byte[1024];
int bytesRead = 0;
int totalBytesRead = 0;

while ((bytesRead = inputStream.read(fileBytes)) > 0) {
outputStream.write(fileBytes, 0, bytesRead);

totalBytesRead += bytesRead;

notifyListenersOnProgress((double)totalBytesRead / (double)getStreamFile().length());
}

很简单,对吧?直到我在大约两个循环后看到此错误:

java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:1.6.0_23]
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109) ~[na:1.6.0_23]
at java.net.SocketOutputStream.write(SocketOutputStream.java:141) ~[na:1.6.0_23]

我在这里做错了什么?

最佳答案

不要手工做这些事情。为此使用 HttpURLConnection,这就是它的用途。创建一个 URL,从中获取 HttpURLConnection,将请求方法设置为“PUT”,设置内容类型,设置内容长度,获取输出流,然后开始写入。

关于java - 尝试写入文件时出现 Broken Pipe 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11405582/

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