使用 HttpUrlConnection 进行抢占式基本身份验证? [英] Preemptive Basic Auth with HttpUrlConnection?

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

问题描述

使用 HttpUrlConnection 使用抢占式基本 http 身份验证的最佳方法是什么.(假设现在我不能使用 HttpClient).

What is the best way to use preemptive basic http authentication using HttpUrlConnection. (Assume for now I can't use HttpClient).

编辑澄清:我正在使用 Base64 编码在请求标头中正确设置 un/pw.是否有任何其他标志或属性需要设置,或者我正在为请求设置基本身份验证标头的事实是抢占式基本身份验证所需的全部内容?

EDIT for clarification: I'm setting the un/pw correctly in the request header using Base64 encoding. Are there any additional flags or properties that need to be set, or is the fact that I'm setting the basic auth headers for the request all that is needed for preemptive basic auth?

推荐答案

如果您使用的是 Java 8 或更高版本,java.util.Base64 可用:

If you are using Java 8 or later, java.util.Base64 is usable:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));  //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);


然后正常使用连接.


Then use the connection as normal.

如果您使用的是 Java 7 或更低版本,则需要一种将字符串编码为 Base64 的方法,例如:

If you're using Java 7 or lower, you'll need a method to encode a String to Base64, such as:

byte[] message = (username+":"+password).getBytes("UTF-8");
String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message);

是的,这就是使用基本身份验证所需的全部操作.上面设置请求属性的代码应该在打开连接后和获取输入或输出流之前立即完成.

Yes, that's all you have to do in order to use Basic Auth. The code above to set the Request Property should be done immediately after opening the connection and before getting the Input or Output streams.

这篇关于使用 HttpUrlConnection 进行抢占式基本身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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