2010-01-26 56 views
4

我想註銷如果你們知道如何使用java.net.Authenticator中的類「註銷」基本認證(BA)。我知道BA沒有註銷方法,您必須關閉並重新打開瀏覽器才能結束會話。問題是,你如何在java代碼中關閉並重新打開瀏覽器?也就是說,我是通過java連接的,而不是borwser,所以如何讓JVM自己去'deauthenticate'?與java.net.Authenticator中

語境:我正在寫一個應用程序來發布推特使用BA多個Twitter帳號。我可以使用java.net。*張貼鳴叫一個帳戶(可以看到它調用我的鑑定者類),但是當我嘗試發佈的tweet第二,我看不到任何第二次調用認證,並且推特被髮射到第一個賬戶。

是否有可能獲得身份驗證重新進行身份驗證,或者這是一個死衚衕?如果是的話,我可能只是最終使用OAuth來代替。

許多預先感謝您可以提供任何見解!

沙恩

static class MyAuthenticator extends Authenticator { 

    private String username, password; 

    public MyAuthenticator(String user, String pass) { 
     username = user; 
     password = pass; 
    } 

    protected PasswordAuthentication getPasswordAuthentication() { 
     System.out.println("Requesting Host : " + getRequestingHost()); 
     System.out.println("Requesting Scheme : " + getRequestingScheme()); 
     System.out.println("Requesting Site : " + getRequestingSite()); 
     return new PasswordAuthentication(username, password.toCharArray()); 
    } 
} 

公共無效鳴叫(AutoTwitterAccount ACC,字符串鳴叫){ Authenticator.setDefault(空);

Authenticator.setDefault(new MyAuthenticator(acc.getUserName(), acc.getPassword())); 
    try { 
     /* First login the session and fire off tweet*/ 
     URL url = new URL(AutoTweeter.TWEET_URL); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("User-Agent", "Mozilla/4.0"); 
     conn.setRequestProperty("User-Agent", AGENT); 
     conn.setRequestProperty("Content-Type", TYPE); 
     conn.setRequestProperty("Content-Length", "" + tweet.length()); 
       ...fire off tweet.... 
     conn.disconnect(); 

再次感謝!

+0

http://www.cafesoft.com/products/cams/tomcat-security.html(它說:「一旦你進入..「) – Bozho 2010-01-26 13:16:40

回答

4

如果身份驗證確實不會再次調用(甚至在重新設定到另一個不工作,這顯然是由於a bug的情況下),那麼你可以放棄身份驗證和send the HTTP Basic Auth header manually

URL url = new URL("http://www.example.com/comment"); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setRequestProperty("Authorization:", 
"Basic "+codec.encodeBase64String(("username:password").getBytes()); 
+0

謝謝Thilo,看起來像錢!我會盡快嘗試。 – user259121 2010-01-26 12:30:05

0

我試過了,但它仍然無法驗證,但我已經用同事的實用工具類,構建HTTP請求自己和它的直接寫入插座,繞過太陽的HTTP類解決此得到。不過謝謝你的回答!

0

如果您使用驗證器代理,請嘗試以下操作:

import org.apache.commons.codec.binary.Base64; 
... 
StringBuilder auth = new StringBuilder("Basic "); 
auth.append(Base64.encodeBase64String((username + ':' + password).getBytes())); 
connection.setRequestProperty("Proxy-Authorization", auth.toString());