Skip to content

Instantly share code, notes, and snippets.

@gbzarelli
Created December 7, 2018 11:46
Show Gist options
  • Save gbzarelli/98c36256d6afd849a00d61e127a14497 to your computer and use it in GitHub Desktop.
Save gbzarelli/98c36256d6afd849a00d61e127a14497 to your computer and use it in GitHub Desktop.
Exemplo de download de arquivo utilizando OkHttp - Example of file download using OkHttp
import me.tongfei.progressbar.ProgressBar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleDownloadFileOkHttp {
//*
private static final String HEADER_AUTHORIZATION = "Authorization";
private static final String HEADER_CONTENT_LENGTH = "Content-Length";
private static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
//*
private static final String FILE_JBOSS = "http://helpdev.com.br/file/15BB358C8E497C0C2BD0B594A1470D84527D75EB/15";
private static final String TOKEN = "Bearer eyJzdWIiOiJudGFsayIsInByaXZpbGVnZXMiOlsiUk9MRV9VU0VSIl19.-nSEkcSbEW4SmXqQ";
public static void main(String[] args) throws IOException {
Request request = new Request.Builder().url(FILE_JBOSS)
.header(HEADER_AUTHORIZATION, TOKEN)
.get().build();
new SampleDownloadFileOkHttp().sampleDownloadOkHttp(request, new File("/home/helpdev"));
}
private void sampleDownloadOkHttp(Request request, File pathToSaveFile) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
Response response = okHttpClient.newCall(request).execute();
if (response.body() == null) {
throw new IOException("no body");
}
String headerContentLength = response.header(HEADER_CONTENT_LENGTH);
final long lengthFile;
if (headerContentLength != null && !headerContentLength.isEmpty()) {
lengthFile = Integer.parseInt(headerContentLength);
} else {
lengthFile = -1;
}
String fileName = System.currentTimeMillis() + ".tmp";
String headerContentDisposition = response.header(HEADER_CONTENT_DISPOSITION);
if (headerContentDisposition != null) {
Pattern regex = Pattern.compile("(?<=filename=\").*?(?=\")");
Matcher regexMatcher = regex.matcher(headerContentDisposition);
if (regexMatcher.find()) {
fileName = regexMatcher.group();
}
}
File fileToSave = new File(pathToSaveFile, fileName);
try {
final ProgressBar progressBar = new ProgressBar(fileName + " downloading...", lengthFile);
progressBar.start();
saveStreamToFile(response.body().byteStream(), fileToSave, progressBar::stepTo);
progressBar.stop();
} catch (IOException io) {
fileToSave.deleteOnExit();
}
}
public interface DownloadNotify {
void downloading(long total);
}
private void saveStreamToFile(InputStream inputStream,
File fileToSave,
DownloadNotify downloadNotify) throws IOException {
saveStreamToFile(inputStream, fileToSave, downloadNotify, 131072, 3_000);
}
private void saveStreamToFile(InputStream inputStream,
File fileToSave,
DownloadNotify downloadNotify,
int sizeBuffer,
int notifyTimeMillis) throws IOException {
try (BufferedInputStream input = new BufferedInputStream(inputStream);
OutputStream output = new FileOutputStream(fileToSave)) {
byte[] data = new byte[sizeBuffer];
long total = 0;
long notify = System.currentTimeMillis();
int count;
while ((count = input.read(data)) != -1) {
total += count;
if ((System.currentTimeMillis() - notify) > notifyTimeMillis) {
downloadNotify.downloading(total);
notify = System.currentTimeMillis();
}
output.write(data, 0, count);
}
downloadNotify.downloading(total);
output.flush();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste</groupId>
<artifactId>teste</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>me.tongfei</groupId>
<artifactId>progressbar</artifactId>
<version>0.7.1</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment