我正在使用rx java和Retrofit,okhttp。 下载内容后,在读取输入sream时“Socket Closed”
尝试不同的方式,如: *从onNext方法获取响应,然后读取输入流
我的代码看起来像这样:
mApi.getPdf(mUserManager.getUserProfile().getAuthToken())
.compose(mRxUtils.applySchedulers())
.subscribe(new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
mApiErrorManager.handleError(e);
}
@Override
public void onNext(ResponseBody downloadPDFModelResponse) {
downloadFile(downloadPDFModelResponse, myFile);
}
});
下载功能看起来像这样:
private void downloadFile(ResponseBody body, File myFile) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = myFile;
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
//int timeCount = 1;
while ((count = bis.read(data)) != -1) { //here getting Socket closed exception
total += count;
int progress = (int) ((total * 100) / fileSize);
mEventBus.post(new DownloadProgress(progress));
output.write(data, 0, count);
}
mEventBus.post(new DownloadProgress(DownloadProgress.COMPLETE));
output.flush();
output.close();
bis.close();
}