我遇到了一个奇怪的问题,也无法进行调试。我已经实现了上传数据流的逻辑,并且正在使用 Volley 进行操作。我稍微定制了一下 HurlStack
和 addBodyIfExists
API 的逻辑,以便能够处理 "application/octet-stream" 类型的主体内容。
我的逻辑是为了向用户发布进度,以便可以更新 UI,指示用户上传的进度,以下是我实现同样功能的逻辑。
int toRead = length; // File length
byte[] data = new byte[4096];
connection.setDoOutput(true);
if(length != -1) {
connection.setFixedLengthStreamingMode(length);
} else {
connection.setChunkedStreamingMode(4096);
}
OutputStream os;
int i;
int count;
os = connection.getOutputStream();
int progress= 0;
try {
for(i = 0; (count= is.read(data)) > 0; ++i) { // is, is not null and contains a valid input stream
os.write(data, 0, count); // at this line am getting unexpected end of stream
progress+= count;
if(i % 20 == 0) {
rs.deliverProgress(progress, 0L);
progress= 0;
}
}
os.flush();
} finally {
if(is != null) {
is.close();
}
if(os != null) {
os.close();
}
}
在执行上述代码时,我遇到了这个问题,尽管我已经验证了输出流不为空,输入流也不为空,但它在第一次读取循环中失败了,我看到它已经读取了4096个字节,然后尝试写入相同的内容。
java.net.ProtocolException: unexpected end of stream
at com.android.okhttp.internal.http.HttpConnection$FixedLengthSink.close(HttpConnection.java:326)
at com.android.okio.RealBufferedSink.close(RealBufferedSink.java:174)
at com.android.okio.RealBufferedSink$1.close(RealBufferedSink.java:142)
非常感谢在调试过程中提供的任何帮助。
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "utf-8")); writer.write(...);
代替os.write(...)
。 - BNK