【问题标题】:Java Authenticator on a per connection basis?Java Authenticator 基于每个连接?
【发布时间】:2010-10-10 15:20:46
【问题描述】:

我正在构建一个与使用基本身份验证的 REST 接口通信的 Eclipse 插件。当身份验证失败时,我想弹出插件的设置对话框并重试。通常我可以使用静态Authenticator.setDefault()为此设置所有HttpURLConnection的身份验证器,但由于我正在编写一个插件,我不想覆盖Eclipse的默认Authenticatororg.eclipse.ui.internal.net.auth);

我想在加载之前设置我的自定义 Authenticator,然后再将 Eclipse 的默认设置放回去,但我想这会导致多线程的各种竞争问题,所以我很快就失去了这个想法。

Google 搜索产生的各种结果基本上告诉我这是不可能的:

Java URLConnection API 应该有一个 setAuthenticator(Authenticator) 方法,以便在需要身份验证的多线程上下文中更轻松地使用此类。

Source

如果应用程序包含很少的第三方插件,并且每个插件都使用自己的 Authenticator,我们应该怎么做?每次调用“Authenticator.setDefault()”方法都会重写之前定义的Authenticator...

Source

有什么不同的方法可以帮助我解决这个问题吗?

【问题讨论】:

  • +1 我也有同样的问题。很烦人!

标签: java httpurlconnection authenticator


【解决方案1】:

另一种方法是自己在连接上执行基本身份验证。

    final byte[] encodedBytes = Base64.encodeData((username + ':' + new String(password)).getBytes("iso-8859-1"));
    final String encoded = new String(encodedBytes, "iso-8859-1");

    connection.setRequestProperty("Authorization", "Basic " + encoded);

这还具有以下优点:在为后续请求提供凭据之前,不需要未经身份验证的请求接收 401。通过请求抢占式身份验证,可以在 apache http-client 中利用类似的行为。

【讨论】:

  • 非常感谢!你拯救了我的一天。 Authenticator.setDefault 是一个完整的 CRIME...
【解决方案2】:

如果 HttpURLConnection 无法实现,我建议使用 Apache 的 httpclient 库。

一个简单的例子:

HttpClient client = new HttpClient();
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("test","test"));
GetMethod getMethod = new GetMethod("http://www.example.com/mylogin");
client.executeMethod(getMethod);
System.out.println(getMethod.getResponseBodyAsString());

【讨论】:

  • 是的,如果 JRE 默认 HttpURLConnection 的这个问题是不可克服的,我已经决定使用 apache commoms http 客户端。不过感谢您的回答!
  • 最后选择第 3 方 Http 类是唯一可行的解​​决方案,所以我会接受你的回答。
猜你喜欢
  • 2015-09-30
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多