import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* javaのSSL証明書を信頼するためのユーティリティクラス
*
*/
public class SslUtil {
//urlからファイルをダウンロードするメソッド
public void downloadFileFromUrl(String fileUrl, String fileName) throws Exception {
URL url = new URL(fileUrl);
SslUtil.ignoreSsl();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(6000);
urlConnection.setReadTimeout(6000);
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("接続リクエストの状態:---------------"+urlConnection.getResponseCode());
throw new RuntimeException("ファイルの読み取りに失敗しました");
}
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.close();
File file = new File("/deployments/" + fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
fileOutputStream.close();
inputStream.close();
System.out.println("ダウンロード成功:" + "/deployments/" + fileName);
}
/**
* HTTPSリクエストのSSL証明書を無視します。openConnectionの前に呼び出す必要があります
*
* @throws Exception
*/
public static void ignoreSsl() throws Exception {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager, X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
}