我正在尝试创建一个将在浏览器中运行、从 URL 下载图像并将其显示给用户的 java jar Applet。我的实现是:
try {
String imageURL = "http://www.google.com/intl/en_ALL/images/logo.gif";
URL url = new URL(imageURL);
img = ImageIO.read(url);
} catch (IOException e) {
System.out.println(e);
}
但这给了我一个安全例外:
java.security.AccessControlException: access denied (java.net.SocketPermission www.google.com:80 connect,resolve)
解决方案:
我已经实现了 Knife-Action-Jesus 的建议,它可以在网络浏览器中运行(但不使用小程序查看器)。
只有小程序查看器我仍然遇到:
java.security.AccessControlException: access denied (java.net.SocketPermission www.google.com:80 connect,resolve)
在浏览器中加载网页时,有一个信任/拒绝对话框,如果我单击信任,则会显示图像。
这些是我正在采取的步骤:
ant makejar
jarsigner -keystore keystore-name -storepass password -keypass password web/LoadImageApp.jar alias-name
jarsigner -verify -verbose web/LoadImageApp.jar
appletviewer web/index.html ## as mentioned above, this gives a security exception. instead, load the webpage in a browser.
jarsigner -verify 的输出是:
Warning: The signer certificate will expire within six months.
332 Thu Jan 07 20:03:38 EST 2010 META-INF/MANIFEST.MF
391 Thu Jan 07 20:03:38 EST 2010 META-INF/ALIAS-NA.SF
1108 Thu Jan 07 20:03:38 EST 2010 META-INF/ALIAS-NA.DSA
sm 837 Thu Jan 07 20:03:38 EST 2010 LoadImageApp$1.class
sm 925 Thu Jan 07 20:03:38 EST 2010 LoadImageApp.class
sm 54 Wed Jan 06 01:28:02 EST 2010 client.policy
s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope
jar verified.
以下是完整的 java 源代码(为了强调这个概念,我删除了所有额外的异常处理/空检查):
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.security.*;
public class LoadImageApp extends JApplet
{
private BufferedImage img;
private final String imageURL = "http://www.google.com/intl/en_ALL/images/logo.gif";
public void init()
{
loadImage();
}
public void paint(Graphics g)
{
if (null != img) { g.drawImage(img, 0, 0, null); }
}
public void loadImage()
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
URL url = new URL(imageURL);
if (null == url)
{
throw new MalformedURLException();
}
img = ImageIO.read(url);
}
catch (Exception e) { e.printStackTrace(); }
return null;
}
});
}
}