import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpsConnectionUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpsConnectionUtil.class);
private HttpsConnectionUtil() {
}
public static File downloadFile(String urlPath, String downloadDir) {
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(urlPath);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
} catch (MalformedURLException e) {
LOGGER.error("Get MalformedURLException.", e);
} catch (IOException e) {
LOGGER.error("Get IOException.", e);
}
File file = null;
if (null == httpURLConnection) {
return file;
}
int responseCode = 404;
try {
responseCode = httpURLConnection.getResponseCode();
} catch (IOException e) {
LOGGER.error("Get response code error.", e);
return file;
}
if (responseCode == HttpURLConnection.HTTP_OK) {
OutputStream out = null;
try (BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream())) {
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf('/') + 1);
String path = downloadDir + '/' + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
int size = 0;
byte[] buff = new byte[1024];
out = new FileOutputStream(file);
while ((size = bin.read(buff)) != -1) {
out.write(buff, 0, size);
}
} catch (IOException e) {
LOGGER.info("Download file error.", e);
} finally {
try {
if (null != out) {
out.close();
}
} catch (IOException e) {
LOGGER.error("Close I/O error.", e);
}
}
} else {
LOGGER.info("Download file: {} failed, responseCode:{}.", urlPath, responseCode);
}
return file;
}
}