2011-12-29 154 views
6

我有一个运行在Tomcat 6中的Java webapp,它从远程URL加载RSS提要。Java代理身份验证

我用Rome处理RSS源和不同格式的我。连接部分看起来像这样:

try{ 
    feedSource = new URL(rssObject.getAsset()); 
}catch(MalformedURLException mue){ 
    logger.error(...); 
    throw mue; 
} 

try{ 
    URLConnection connection = feedSource.openConnection(); 
    feed = new SyndFeedInput().build(new XmlReader(connection)); 
}catch(Exception){handle...} 

的代码工作正常,但在这个新的客户,他们使用代理。

为了使用代理,我设置http.proxyHost和proxyPort系统属性:

System.setProperty("http.proxyHost", proxyHost); 
System.setProperty("http.proxyPort", proxyPort); 
System.setProperty("https.proxyHost", proxyHost); 
System.setProperty("https.proxyPort", proxyPort); 

HTTP GET是对代理制作好的,但现在我得到一个HTTP 502错误(坏网关或相似的东西)。

分析使用Wireshark的HTTP交换,我注意到,代理需要验证。它发送一个HTTP 507. Java以某种方式尝试进行身份验证,但它使用了错误的用户名和密码。它似乎使用主机名作为用户名,至于我不知道的密码。

于是,我就实现指定用户名+密码的身份验证方法:

Authenticator.setDefault(new Authenticator() { 
      @Override 
      protected PasswordAuthentication getPasswordAuthentication() { 
       logger.info(MessageFormat.format("Generating PasswordAuthentitcation for proxy authentication, using username={0} and password={1}.", username, password)); 
       return new PasswordAuthentication(username, password.toCharArray()); 
      } 
     }); 

现在我的问题是,它会被忽略。 getPasswordAuthentication方法永远不会被调用。我没有看到日志文件中的日志语句,并使用Wireshark,我可以看到它仍然使用主机名作为用户名。

为什么?看起来java不知怎么的尝试自己进行身份验证,而没有咨询Authenticator。

代理似乎是使用NTLM用于认证的MS设备。在java中有一些内置的机制来处理这个问题吗?运行该应用程序的机器是Win Server 2008 R2。

回答

12

我们在这里做了同样的基于NTLM的代理进行身份验证。

代理上的身份验证实际上是一种正常的HTTP基本验证

我们使用以下方法:

protected URLConnection newURLConnection(URL pURL) throws IOException { 
    URLConnection urlConnection = super.newURLConnection(pURL); 

    String auth = new String(Base64.base64Encode(new String("username:password").getBytes())); 
    auth = "Basic " + auth; 
    urlConnection.setRequestProperty("Proxy-Connection","Keep-Alive"); 
    urlConnection.setRequestProperty("Proxy-Authorization",auth); 
    return urlConnection; 
} 

也就是说,与代理JVM设置在一起,并获得成功。

http://en.wikipedia.org/wiki/Basic_access_authentication

+0

非常感谢。它也适用于我们。 – 2011-12-29 16:05:36