Skip to content

Instantly share code, notes, and snippets.

@leoleozhu
Last active January 11, 2022 10:57
Show Gist options
  • Save leoleozhu/4b707fe9beb4fea43dfd48cc53770a8e to your computer and use it in GitHub Desktop.
Save leoleozhu/4b707fe9beb4fea43dfd48cc53770a8e to your computer and use it in GitHub Desktop.
Download file with HTTP resumable
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URL;
public class DownloadUtils {
OkHttpClient client = new OkHttpClient();
public void downloadResumable(URL url, File file, int maxTry) throws IOException {
maxTry = Math.max(maxTry, 1);
boolean finished = false;
long contentLength = getUrlContentLength(url);
while (!finished) {
long currentLength = getFileLength(file);
// check current file less than declared size
if (currentLength >= contentLength) {
finished = true;
break;
}
boolean isResume = currentLength > 0;
Request.Builder requestBuilder = new Request.Builder();
if (isResume) {
requestBuilder.header("Range", "bytes=" + currentLength + "-");
}
Request request = requestBuilder.url(url).build();
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
try (InputStream inputStream = body.byteStream();
OutputStream outputStream = new FileOutputStream(file, isResume)) {
IOUtils.copy(inputStream, outputStream);
finished = true;
} catch (IOException ioException) {
maxTry--;
if (maxTry <= 0) {
throw ioException;
}
}
}
}
long getUrlContentLength(URL url) throws IOException {
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.url(url).head().build();
Response response = client.newCall(request).execute();
return Long.parseLong(response.header("Content-Length"));
}
long getFileLength(File file) {
return file.exists() ? file.length() : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment