如何利用HttpURLConnection类来处理HTTP认证? [英] How to handle HTTP authentication using HttpURLConnection?
问题描述
我在写一个Java客户端的POST,需要一个HTTP服务器的验证。结果
我必须至少支持以下三种身份验证方法:基本,摘要或议付。此外,该POST可能(超过2MB)非常大,所以我需要使用流媒体。
至于被记录为<一个href=\"http://download.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html#setFixedLengthStreamingMode%28int%29\">HttpURLConnection
I'm writing a Java client that POSTs to a HTTP server that requires authentication.
I have to support at least the following three authentication methods: Basic, Digest or Negotiate. Additionally the POST may be very large (over 2MB), so I need to use streaming.
As is documented for HttpURLConnection
当使能输出流,认证和重定向不能自动处理。读取响应时,如果需要验证或重定向的Htt pretryException将被抛出。
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.
所以,我需要处理验证自己。我搜索,搜查了一遍,换一种方式来聘请,已经codeD,类 - 却发现没办法...
So, I need to handle authentication myself. I searched, and searched again, for a way to employ the, already coded, classes - but found no way...
我可以采摘从<一个所需的源href=\"http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/f7afe7a5e086/src/share/classes/sun/net/www/protocol/http/\">here (因为它们是GPLv2加的Classpath例外)。这是正确的方式?
I could just pluck the needed sources from here (as they are GPLv2 with Classpath exception). Is this the right way?
感谢。
推荐答案
您需要的输出流?在 HttpURLConnection类
最绝的支持与验证器
类的身份验证,请参阅:的Http认证。
Do you need output streaming? The HttpURLConnection
most definitely supports authentication with the Authenticator
class, see: Http Authentication.
更新:若验证器
不是一个选项,您可以手动执行HTTP通过增加一个额外的头到你的HTTP请求的基本身份验证。请尝试以下code(未经测试):
Update: In case the Authenticator
is not an option, you can manually do HTTP basic authentication by adding an extra header to your HTTP request. Try the following code (untested):
String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);
uc.connect();
这篇关于如何利用HttpURLConnection类来处理HTTP认证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!