我有一些带有图像的 URL。此图像在每个请求期间更新(即,对(相同)URL 的每个请求都返回一个新图像)。比如说,这个 URL 指向 CAPTCHA。我的目标是在我的程序中加载和显示几个这样的图像。
以下代码将这些图像加载到我的本地文件系统并且工作正常(也就是说,所有图像都是不同的、唯一的):
String filePath;
String urlPath;
int numOfFilesToDownload;
//Here filePath and urlPath are initialized.
//filePath points to the directory, where to save images
//urlPath is the url from where to download images
//numOfFilesToDownload is the number of files to download
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing connection
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Downloading image
try(InputStream is = conn.getInputStream();
FileOutputStream os = new FileOutputStream(filePath + "img" + i + ".jpg")){
int b;
while((b = is.read()) != -1)
os.write(b);
}
}
但是当我尝试以下事情时,发生了一些奇怪的事情:
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
在后一种情况下,每个对话框都包含相同的图像,即在第一次迭代期间下载的图像。
此外,实验表明,如果将“?r=”连接到 urlPath(即简单的 GET 请求参数),则 url 仍然有效。下面的代码似乎是有效的,并且完全符合它的功能(即显示的每个图像都与前一个不同):
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath + "?r=" + i);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
因此我可以得出一个结论,ImageIcon 以某种方式记住了它处理的 URL,并且根本不费心执行相同的工作两次......为什么以及如何?javadocs 中没有关于它的内容。