簡體   English   中英

使用 API 后訪問 java 中的不記名令牌

[英]Accessing bearer token in java using post API

我必須調用url來獲取訪問令牌以調用后續 API。 此令牌端點通過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

我無法在 java 中消費上述內容。 我嘗試了很多代碼,但沒有一個工作。 可以嗎,請幫我一些鏈接。 我是java的新手,並且很掙扎。 下面是我使用的代碼。 它不工作。

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());
    }
    
}

}

首先,我不知道這行encodedBytes = Base64.encode(authorization.getBytes(), 0); 在您的機器上編譯(沒有Base64#encode方法)。

假設您使用 Java 1.8+,更改:

byte[] encodedBytes;
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + encodedBytes;
hc.setRequestProperty("Authorization", authorization)

String encodedCredentials = Base64.getEncoder().encodeToString(authorization.getBytes());
hc.setRequestProperty("Authorization", "Basic " + encodedCredentials);

應該做的伎倆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM