jdk1.7设置URLConnection的TLS

jdk1.7无法下载https的图片,需要修改下代码。兼容TLSv1.2。

/**
*
* @param imageUrl
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static File downloadImageToTempFile(String imageUrl) throws IOException, NoSuchAlgorithmException, KeyManagementException {
// 创建一个临时文件
File tempFile = File.createTempFile("image", ".jpg");
//tempFile.deleteOnExit(); // 确保在程序退出时删除临时文件

// 打开 URL 连接
URL url = new URL(imageUrl);
InputStream inputStream;
if (imageUrl.startsWith("https")) {
SSLContext sc = SSLContext.getInstance("TLSv1.2"); //$NON-NLS-1$
sc.init(null, null, null);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(sc.getSocketFactory());
inputStream = connection.getInputStream();
}else {
URLConnection urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
}


// 写入临时文件
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

// 关闭流
outputStream.close();
inputStream.close();

// 返回临时文件
return tempFile;
}

// 测试main方法

public static void main(String[] args) throws IOException {

String imageUrl = "https://oss.ta.com/m/029388.jpg";
String  imageUrl2 = "http://192.168.1.111:9000/BJTL-044%20(1).jpg";
try {
File tempFilePath = HttpUtils.downloadImageToTempFile(imageUrl);
System.out.println("Image downloaded to temporary file: " + tempFilePath);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to download image.");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}

posted @ 2024-04-10 13:10  黎明的太阳  Views(154)  Comments(0Edit  收藏  举报