preemptive基本验证与HttpURLConnection类?基本、preemptive、HttpURLConnection

2023-09-12 02:22:16 作者:宁愿把你宠坏

什么是使用HttpURLConnection类使用preemptive基本的HTTP认证的最佳途径。 (假设现在我不能使用HttpClient的)。

编辑澄清:我设置了UN / PW正确使用Base64编码的请求头。是否有需要进行设置,或者是,我设置的是需要preemptive基本身份验证的基本认证头的请求的所有的任何其他标​​志或属性?

解决方案

  HttpURLConnection的连接=(HttpURLConnection类)新的网址(URL).openConnection();
字符串连接codeD = Base64.en code(用户名+:+密码);
connection.setRequestProperty(授权,基本+ EN codeD);
 

然后用连接正常。

Base64.en code(字符串)将是基地64一些方法来连接codeA字符串。

是的,这就是你必须做的,以使用基本身份验证。在code以上设置请求物业应立即后打开连接,并获取输入或输出流之前完成。

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

吴恩达机器学习视频课提纲 随堂选择练习题 week10应用机器学习 week11设计机器学习

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?

解决方案

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.encode(username+":"+password);
connection.setRequestProperty("Authorization", "Basic "+encoded);

Then use the connection as normal.

Base64.encode(String) would be some method to encode a string in Base 64.

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.