2011-02-03 17 views
32

我正在写一个Java客户端,发布到需要身份验证的HTTP服务器
我必须至少支持以下三种身份验证方法:基本,摘要或协商。此外,POST可能非常大(超过2MB),所以我需要使用流媒体。 正如记载为HttpURLConnection如何使用HttpURLConnection处理HTTP身份验证?

When output streaming is enabled, authentication and redirection cannot be handled automatically. A HttpRetryException will be thrown when reading the response if authentication or redirection are required.

所以,我需要处理验证自己。我搜索,并再次搜索的方式来雇用,已编码的类 - 但没有办法...

我可以从here(因为他们是GPLv2类路径异常)采摘所需的来源。这是正确的方式吗?

谢谢。

+0

什么样的认证? HTTP基本身份验证?还是更复杂的东西? – Tim 2011-02-03 06:58:17

+0

可以是_Basic_,_Digest_或_Negotiate_。基本是**简单**。另外两个不是:) – Opher 2011-02-03 12:00:07

回答

47

你需要输出流吗? HttpURLConnection绝对支持Authenticator类的认证,请参阅:Http Authentication

更新:如果Authenticator不是一个选项,您可以通过向您的HTTP请求添加额外的标头来手动执行HTTP基本认证。试试下面的代码(未经测试):

String userPassword = username + ":" + password; 
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); 
URLConnection uc = url.openConnection(); 
uc.setRequestProperty("Authorization", "Basic " + encoding); 
uc.connect(); 
+0

是的。我的** POST **包含一个可能超过2MB大小的文件。 – Opher 2011-02-03 12:02:38

4

相关的@垫的评论:

这是我的球队,我用一个例子:

import org.apache.commons.codec.binary.Base64; 

HttpGet getRequest = new HttpGet(endpoint); 
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding()); 

private String getBasicAuthenticationEncoding() { 

     String userPassword = username + ":" + password; 
     return new String(Base64.encodeBase64(userPassword.getBytes())); 
    } 

希望它能帮助!