Java вызывает исключение SSLHandshakeException при попытке прочитать URL-адрес изображенияJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Java вызывает исключение SSLHandshakeException при попытке прочитать URL-адрес изображения

Сообщение Anonymous »

Я пытался получить изображение по URL-адресу, например. https://localhost:8443/image/01/example.png, а затем нарисуйте на нем строку. Однако я всегда нажимаю SSLHandshakeException, если не отключил проверку сертификата SSL. Ниже приведен мой код с отключениемSSLCertificateChecking():

Код: Выделить всё

private String drawTextOnImage(String imagePath, String rate, String lastUpdatedDate) throws Exception {
URL url = new URL(imagePath);
// Fetch the image from the URL
BufferedImage image = null;
try {
disableSSLCertificateChecking();
image = ImageIO.read (url.openStream());
// Continue processing
} catch (Exception e) {
logger.error("Error loading image from URL: " + imagePath, e);
throw new Exception("Failed to load image", e);
}
// Get the graphics object from image
Graphics2D g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

//Draw auto sweep rate
g.setFont(new Font("Times New Roman", Font.BOLD, 110)); // Set font size and style
g.setColor(new Color(24, 59, 155)); // Set text color
g.drawString(rate, 100, 526);

// Draw last updated date
g.setFont(new Font("Times New Roman", Font.ITALIC, 30)); // You can set a different font for the second text
g.setColor(Color.WHITE); // You can set a different color for the second text
g.drawString(lastUpdatedDate, 100, 600);
g.dispose();

// Convert the modified image to a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
byte[] imageBytes = baos.toByteArray();

// Encode the byte array to Base64 string
return Base64.getEncoder().encodeToString(imageBytes);

}

private void disableSSLCertificateChecking() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// Optional: Disable hostname verification as well
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
}
Есть ли обходной путь без отключения проверки SSL, позволяющей выполнять чтение и рисование изображения?

Подробнее здесь: https://stackoverflow.com/questions/791 ... -image-url
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»