我正在嘗試編寫一個非常簡單的應用程序,該應用程序會通過HTTP將PUT請求上傳到我的服務器之一。以下是我的代碼的樣子:嘗試寫入文件時發生斷管異常
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]
我在做什麼錯在這裏?
由於上傳要求,我_要設置內容長度。我能否像正常輸出流一樣寫,這樣我就可以測量上傳進度了嗎? – 2012-07-10 16:08:56
@TKKocheran不,你不知道。 Java將自動設置內容長度。自己設置只會提供一個錯誤的機會。如果這是一個很大的轉移,我會設置分塊傳輸模式。是的,您可以監視輸出流的進度。 – EJP 2012-07-11 00:56:41