简体   繁体   中英

Accessing bearer token in java using post API

I have to call a url to get access token to call subsequent APIs. This token end point is secured with 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. 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. 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); compiles on your machine (there is no Base64#encode method).

Assuming your using Java 1.8+, changing:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM