2011-04-05 38 views
1

我想为应用程序添加“注销”功能,并且这样做需要忘记所有密码。替换Authenticator似乎没有效果,因为getPasswordAuthentication不会再被调用。似乎有一个密码缓存,但我找不到或清除它的方式。下面是测试情况:通过java.net.Authenticator设置清除密码

import java.net.*; 
import java.io.*; 

class Main { 
    public static void main(String[] args) throws MalformedURLException, IOException { 
     Authenticator.setDefault(new Authenticator() { 
      public PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication("stack", "overflow".toCharArray()); 
      } 
     }); 

     URLConnection connection = new URL("http://devio.us/~ricky/stackoverflow-protected/nothingtosee.html").openConnection(); 
     System.out.println(new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")).readLine()); 

     Authenticator.setDefault(new Authenticator() { 
      public PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication("no", "way".toCharArray()); 
      } 
     }); 

     connection = new URL("http://devio.us/~ricky/stackoverflow-protected/nothingtosee.html").openConnection(); 
     System.out.println(new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")).readLine()); 

     //This second line ideally should not succeed. I.e., the results are <html>\n<html>, but only the first <html> should be seen. 
    } 
} 

该网站是一个我和控制的情况下,它消失以任何理由:堆栈/溢出是有效的,无/办法是不使用的.htaccess。如果您知道更标准的参考站点,请随时更改我的代码或建议更换。

回答

1

您可以尝试设置空身份验证器。以下是Java Doc规范:

setDefault public static void setDefault(Authenticator a)设置代理或HTTP服务器请求身份验证时将由网络代码使用的身份验证器。 首先,如果存在安全管理器,则使用NetPermission(“setDefaultAuthenticator”)权限调用其checkPermission方法。这可能会导致java.lang.SecurityException。

参数: a - 要设置的认证码。如果a为空,则任何先前设置的认证者都被删除。

+0

我需要一个身份验证器,以便我可以提示新用户输入用户名/密码。无论如何,我不认为这是有效的,因为认证者的方法甚至不是第二次被调用。 – 2011-12-08 06:51:51

+0

连接获取流失败后,您应该将认证码重置为空。并提示用户下次再次输入用户名/密码。我认为这取决于你的程序逻辑控制。 – hejiaming007 2011-12-23 13:48:34