如何在Java Applet中进行网站身份验证?

时间:2012-06-08 06:33:02

标签: java java-ee applet http-authentication

我有一台无线IP摄像头,我想制作自己的网页来显示其直播。 流的地址是"http://192.168.1.2:8082/index.cgi"(假设),它需要用户身份验证。这意味着当我们在浏览器中输入上述URL时,它会要求输入用户名和密码。

所有我想要的是制作一个java applet,在加载java applet时,它应该验证URL并显示图像/流。

这是情况,现在基本问题是

问:如何在Java applet中进行Http身份验证?

我会感谢每一个答案。

1 个答案:

答案 0 :(得分:1)

您可以通过制作HttpURLConnection并在网址上附加用户名和密码来实现。为:

URL myURL = new URL("http://192.168.1.2:8082/index.cgi?username=user&password=");
HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection();
myConnection.setDoOutput(false);
int status = ((HttpURLConnection) myConnection).getResponseCode();

或者(不是将用户名/密码附加到url),您可以尝试(不确定是否允许在Applet中)为http请求设置默认验证器,如下所示:

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});

您也可以使用非常容易使用的Apache HttpComponents HttpClient。要了解有关HTTP请求如何在Java中工作的更多信息,请参阅此answer