套接字关闭异常android

时间:2017-02-28 05:29:58

标签: android rx-java retrofit2 okhttp3

我正在使用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();


}

1 个答案:

答案 0 :(得分:0)

最后我得到了答案来自此链接,如何使用RX-Java进行下载并进行改造

Downloading file using RX-Java and retrofit

相关问题