downloadFileHttpsConnection("https://www.test.de/_test_/ceck.apk", "C:/Users/Test/Desktop/Mull");
/**
* Downloads a file from a URL
* @param fileURL HTTP URL of the file to be downloaded
* @param saveDir path of the directory to save the file
* @throws IOException
*/
public static void downloadFileHttpsConnection(String fileURL, String saveDir)
throws IOException {
final int BUFFER_SIZE = 4096;
URL url = new URL(fileURL);
HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
int responseCode = httpsConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpsURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpsConn.getHeaderField("Content-Disposition");
String contentType = httpsConn.getContentType();
int contentLength = httpsConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpsConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpsConn.disconnect();
}