[英]Accessing bearer token in java using post API
I have to call a url
to get access token to call subsequent APIs.我必须调用
url
来获取访问令牌以调用后续 API。 This token end point is secured with basic authentication
.此令牌端点通过
basic authentication
进行保护。
token endpoint:- https://xxxxxx.identity.c9dev2.oc9qadev.com/oauth2/v1/token
username: "xxx-ccc"
password: "avcdada"
grant_type: client_credentials
scope: https://xxxxxx.digitalassistant.oci.oc-test.com/api/v1
request type: POST
I am not able to consume above in java.我无法在 java 中消费上述内容。 i tried many codes but none of them working.
我尝试了很多代码,但没有一个工作。 Can you please, please help me with some link.
可以吗,请帮我一些链接。 I am new to
java
and struggling a lot.我是
java
的新手,并且很挣扎。 Below is the code which I used.下面是我使用的代码。 Its not working.
它不工作。
package postapicall;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class PostApi1 {
public static void main(String []args)
{
try
{
String authorization = "";
String url= "https://idcs-82972921e42641b1bf08128c3d93a19c.identity.c9dev2.oc9qadev.com/oauth2/v1/token";
String username = "idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0_APPID";
String password = "244ae8e2-6f71-4af2-b5cc-9110890d1456";
URL address = new URL(url);
HttpURLConnection hc = (HttpURLConnection) address.openConnection();
hc.setDoOutput(true);
hc.setDoInput(true);
hc.setUseCaches(false);
if (username != null && password != null) {
authorization = username + ":" + password;
}
if (authorization != null) {
byte[] encodedBytes;
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + encodedBytes;
hc.setRequestProperty("Authorization", authorization);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
First of all, I don't know how the line encodedBytes = Base64.encode(authorization.getBytes(), 0);
首先,我不知道这行
encodedBytes = Base64.encode(authorization.getBytes(), 0);
compiles on your machine (there is no Base64#encode
method).在您的机器上编译(没有
Base64#encode
方法)。
Assuming your using Java 1.8+, changing:假设您使用 Java 1.8+,更改:
byte[] encodedBytes;
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + encodedBytes;
hc.setRequestProperty("Authorization", authorization)
to至
String encodedCredentials = Base64.getEncoder().encodeToString(authorization.getBytes());
hc.setRequestProperty("Authorization", "Basic " + encodedCredentials);
should do the trick.应该做的伎俩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.