16

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

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

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

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

来源

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

来源

是否有任何不同的方法可以帮助我克服这个问题?

4

2 回答 2

11

如果 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());
于 2009-03-01T16:19:01.937 回答
2

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

    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);

This would also have the advantage of not requiring an unauthenticated request to receive a 401 before providing the credential on a subsequent request. Similar behavior can be leveraged in the apache http-client by requesting preemptive authentication.

于 2013-03-01T14:51:23.920 回答