49 lines
2.2 KiB
Java
49 lines
2.2 KiB
Java
import java.io.IOException;
|
|
import java.net.HttpURLConnection;
|
|
import java.net.MalformedURLException;
|
|
import java.net.URI;
|
|
import java.net.URISyntaxException;
|
|
import java.net.URL;
|
|
|
|
public record HTTPConnection() {
|
|
public static HttpURLConnection open(String _url) throws IOException {
|
|
URL url;
|
|
try {
|
|
url = new URI(_url).toURL();
|
|
} catch (MalformedURLException | URISyntaxException e) {
|
|
throw new IllegalArgumentException("Invalid URL format: " + _url, e);
|
|
}
|
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
|
connection.setConnectTimeout(5000); // 5 seconds
|
|
connection.setReadTimeout(5000); // 5 seconds
|
|
// Use default SSL socket factory for secure connections
|
|
if (connection instanceof javax.net.ssl.HttpsURLConnection) {
|
|
javax.net.ssl.SSLContext sslContext;
|
|
try {
|
|
sslContext = javax.net.ssl.SSLContext.getInstance("TLS");
|
|
sslContext.init(null, new javax.net.ssl.TrustManager[] {
|
|
new javax.net.ssl.X509TrustManager() {
|
|
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
|
return null;
|
|
}
|
|
|
|
public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
|
|
String authType) {
|
|
}
|
|
|
|
public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
|
|
String authType) {
|
|
}
|
|
}
|
|
}, new java.security.SecureRandom());
|
|
((javax.net.ssl.HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
|
|
} catch (Exception e) {
|
|
throw new IOException("Failed to create SSL context", e);
|
|
}
|
|
}
|
|
if (connection instanceof javax.net.ssl.HttpsURLConnection) {
|
|
((javax.net.ssl.HttpsURLConnection) connection).setHostnameVerifier((hostname, session) -> true);
|
|
}
|
|
return connection;
|
|
}
|
|
}
|