CredentialsProvider:检查请求的凭据是否适用于代理

时间:2016-08-25 17:02:05

标签: java apache-httpclient-4.x

我想在CredentialsProvider上安装AbstractHttpClient代理java.net.Authenticator。 从Authenticator请求凭据时,必须指定Authenticator.RequestorType

我的Authenticator包含以下逻辑:

if ( requestorType == RequestorType.PROXY ){
  //retrieve credentials from some configuration
} else{
  //pop up a dialog and ask the user for credentials
}

这适用于通过标准java.net类进行的连接。

我无法找到如何在RequestorType中确定正确的CredentialsProvider。查看SystemDefaultCredentialsProvider的源代码,他们也不能这样做,只需要两次凭证:

PasswordAuthentication systemcreds = 
  getSystemCreds(authscope, RequestorType.SERVER);

if (systemcreds == null) {
    systemcreds = getSystemCreds(authscope, RequestorType.PROXY);

这意味着当通过代理进行连接时,我的Authenticator会显示一个对话框,询问代理凭据,而不是从文件中检索它们。

是否有可靠的方法可以在CredentialsProvider中确定是否为代理请求凭据?

我能想到的最好的方法是尝试从AuthScope重新构建URI并自己查询ProxySelector。但我怀疑我的AuthscopeURI转换没有错误。

RequestorType[] requestorTypes = new RequestorType[]{
    RequestorType.SERVER,
    RequestorType.PROXY
};

ProxySelector defaultProxySelector = ProxySelector.getDefault();
if ( defaultProxySelector != null ){
  try{
    //Hmm, that sounds very dodgy but the AuthScope does not contain any extra information
    URI httpURI = URI.create("http://" + aAuthScope.getHost() + ":" + aAuthScope.getPort());
    URI httpsURI = URI.create("https://" + aAuthScope.getHost() + ":" + aAuthScope.getPort());

    List<Proxy> proxies = new ArrayList<>(defaultProxySelector.select(httpURI));
    proxies.addAll(defaultProxySelector.select(httpsURI));
    for (Proxy proxy : proxies) {
      if (proxy.type() != Proxy.Type.HTTP) {
        requestorTypes = new Authenticator.RequestorType[]{Authenticator.RequestorType.PROXY};
      }
    }
  } catch (IllegalArgumentException e){
    //ignore
  }
}

如果需要,我可以将HttpResponseInterceptorHttpRequestInterceptor个实例添加到AbstractHttpClient

0 个答案:

没有答案