From memory using Retrofit 2 to download a file

I have a pdf viewer application where I need to download large pdf files (e.g. 136mb). For this process, I use retrofit2-beta2. The problem is that I always run out of memory. How can I clarify that I will upload a large file, just give me a byteStream?

My interface:

@GET("url")
Call<ResponseBody> getData(params);

I have a ProgressResponseBody class that extends ResponseBody and I set progressListener here to update my progress bar,

and in function onResponseI just get an InputStream as

InputStream input = response.body().byteStream();
FileOutputStream out = new FileOutputStream(file);
int bufferSize=1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while (len = input.read(buffer) != -1) {
    out.write(buffer,0,len);
} 
if(out!=null)
    out.close();

UPDATE

I added @Stream to the interface, but now I get a NetworkOnMainThreadException in ProgressResponseBody.java The error is called in super.read (sink, byteCount); row. How can I put this in a separate thread?

@Override
    public BufferedSource source() throws IOException {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
                return bytesRead;
            }
        };
    }
+4
1

@Streaming , raw ResponseBody.

@Streaming
@GET("url")
Call<ResponseBody> getData(params);
+3

Source: https://habr.com/ru/post/1615499/


All Articles