use of com.tvd12.ezyhttp.client.exception.DownloadCancelledException in project ezyhttp by youngmonkeys.
the class HttpClient method download.
private void download(HttpURLConnection connection, String fileURL, OutputStream outputStream, DownloadCancellationToken cancellationToken) throws Exception {
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
throw processDownloadError(connection, fileURL, responseCode);
}
try (InputStream inputStream = connection.getInputStream()) {
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
if (cancellationToken.isCancelled()) {
break;
}
outputStream.write(buffer, 0, bytesRead);
}
}
if (cancellationToken.isCancelled()) {
throw new DownloadCancelledException(fileURL);
}
}
use of com.tvd12.ezyhttp.client.exception.DownloadCancelledException in project ezyhttp by youngmonkeys.
the class HttpClient method download.
private String download(HttpURLConnection connection, String fileURL, File storeLocation, DownloadCancellationToken cancellationToken) throws Exception {
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
throw processDownloadError(connection, fileURL, responseCode);
}
String disposition = connection.getHeaderField("Content-Disposition");
String fileName = getDownloadFileName(fileURL, disposition);
Files.createDirectories(storeLocation.toPath());
File storeFile = Paths.get(storeLocation.toString(), fileName).toFile();
File downloadingFile = new File(storeFile + ".downloading");
Path downloadingFilePath = downloadingFile.toPath();
Files.deleteIfExists(downloadingFilePath);
Files.createFile(downloadingFilePath);
try (InputStream inputStream = connection.getInputStream()) {
try (FileOutputStream outputStream = new FileOutputStream(downloadingFile)) {
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
if (cancellationToken.isCancelled()) {
break;
}
outputStream.write(buffer, 0, bytesRead);
}
}
}
if (cancellationToken.isCancelled()) {
Files.deleteIfExists(downloadingFilePath);
throw new DownloadCancelledException(fileURL);
}
Files.move(downloadingFile.toPath(), storeFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
return fileName;
}
Aggregations