如何使用 HttpURLConnection 处理 HTTP 身份验证? [英] How to handle HTTP authentication using HttpURLConnection?

查看:28
本文介绍了如何使用 HttpURLConnection 处理 HTTP 身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Java 客户端,该客户端向需要身份验证的 HTTP 服务器发送 POST 请求.
我必须至少支持以下三种身份验证方法:Basic、Digest 或 Negotiate.此外,POST 可能非常大(超过 2MB),所以我需要使用流媒体.正如 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

启用输出流时,无法自动处理身份验证和重定向.如果需要身份验证或重定向,读取响应时将抛出 HttpRetryException.

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.

所以,我需要自己处理身份验证.我搜索并再次搜索,以寻找一种使用已经编码的类的方法 - 但找不到任何方法......

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...

我可以从 此处(因为它们是 GPLv2,但 Classpath 例外).这是正确的方法吗?

I could just pluck the needed sources from here (as they are GPLv2 with Classpath exception). Is this the right way?

谢谢.

推荐答案

您需要输出流吗?HttpURLConnection 绝对支持使用 Authenticator 类进行身份验证,请参阅:Http 身份验证.

Do you need output streaming? The HttpURLConnection most definitely supports authentication with the Authenticator class, see: Http Authentication.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆