如何使用Java代码设置基本身份验证(用户名和密码):

huangapple go评论63阅读模式
英文:

How to set Basic Auth (Usernama and password) using java code

问题

目前我正在进行以下设置:

    connection.setRequestProperty("Authorization", "Basic NDUwNjMyOTc6U2hyaXNo2weQDEy");

Basic NDUwNjMyOTc6U2hyaXNo2weQDEy——我用 Postman 生成了这部分内容,但其中包含了用户名和密码。

如何使用 Java 生成这个 Auth Basic NDUwNjMyOTc6U2hyaXNo2weQDEy,并在 setRequestProperty 中传递它。

提前谢谢 如何使用Java代码设置基本身份验证(用户名和密码):

英文:

currently i am setting as below:

connection.setRequestProperty("Authorization", "Basic NDUwNjMyOTc6U2hyaXNo2weQDEy"); 

Basic NDUwNjMyOTc6U2hyaXNo2weQDEy"----------This part i have generated using postman. but it contains user name and password.

How to generate this Auth Basic NDUwNjMyOTc6U2hyaXNo2weQDEy using java and pass it in setRequestProperty.

Thanks in advance 如何使用Java代码设置基本身份验证(用户名和密码):

答案1

得分: 3

基本身份验证头部是通过使用 base64 编码的 username:password 生成的,
头部授权值可以按以下方式生成:

Encoder encoder = Base64.getEncoder();
String originalString = username + ":" + password;
String encodedString = encoder.encodeToString(originalString.getBytes());

String headerAuthorization = "Basic " + encodedString;
英文:

The basic auth header is generated from username:password using base 64,
the header authorization value could be generated like so:

Encoder encoder = Base64.getEncoder();
String originalString = username+":"+password;
String encodedString = encoder.encodeToString(originalString.getBytes());

String headerAthorization="Basic "+encodedString;

答案2

得分: 0

你添加头部 Basic ENCODED,其中编码是 "user:password" 的base64编码。
参考示例:https://github.com/jcabi/jcabi-http/blob/master/src/main/java/com/jcabi/http/wire/BasicAuthWire.java#L123。

英文:

You add header Basic ENCODED, where the encoded is base64 of "user:password".
See https://github.com/jcabi/jcabi-http/blob/master/src/main/java/com/jcabi/http/wire/BasicAuthWire.java#L123 for example.

huangapple
  • 本文由 发表于 2020年8月17日 21:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63452324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定