我想知道你们中是否有人知道如何使用java.net.Authenticator类“注销”基本身份验证(BA)。我知道BA没有注销方法,您必须关闭并重新打开浏览器才能结束会话。问题是,如何在java代码中“关闭并重新打开浏览器”?也就是说,我是通过java连接的,而不是borwser,那么我如何让JVM 'deauthenticate‘它自己呢?
上下文:我正在编写一个应用程序,使用BA向多个twitter帐户发布推文。我可以使用java.net.*为一个帐户发布tweet (并且可以看到它调用了我的身份验证器类),但是当我尝试发布第二个帐户的tweet时,我看不到对身份验证器的任何第二次调用,并且tweet get被触发到第一个帐户。
有没有可能让验证器重新进行身份验证,或者这是一个死胡同?如果是这样的话,我可能最终会改用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());
}
}public void tweet(AutoTwitterAccount acc,String tweet) { Authenticator.setDefault(null);
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();再次感谢!
发布于 2010-01-26 18:42:09
如果验证器确实没有再次被调用(甚至将它重置为另一个也不起作用,这显然是由于a bug造成的),那么您可以放弃Authenticator和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());发布于 2010-02-08 23:58:41
我试过了,但它仍然不能进行身份验证,但我已经绕过了这个问题,我使用一个同事实用程序类自己构造HTTP请求,并将其直接写入套接字,绕过了Sun的Http类。不过,还是要谢谢你的回答!
发布于 2013-05-01 03:17:11
如果要将Authenticator用于代理,请尝试以下操作:
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());https://stackoverflow.com/questions/2138686
复制相似问题