Base64 类型未定义方法 encode(byte[], int)。 Post API 来电

The method encode(byte[], int) is undefined for the type Base64. Post API call

如何解决代码中这一行的错误

encodedBytes = Base64.encode(authorization.getBytes(), 0);  it is saying undefined method.

下面是完整的代码。

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

}

基本要求是我必须通过使用 POST 方法调用上面的端点来接收 bearer token。我正在发送用户名和密码,在 return 我想要来自端点的令牌。

错误消息准确地说明了问题所在:

The method encode(byte[], int) is undefined for the type Base64

告诉你Base64上没有签名为encode(byte[], int)的方法-Class.

让我们看一下Base64 javadocs(假设您使用的是java 8)。 我根本找不到任何名为“encode”的方法,所以 java 它的错误消息似乎是正确的。

但是,有一些静态方法可以像这样获得实际的编码器:

Base64.Encoder encoder = Base64.getEncoder();

此编码器提供您需要的实际编码方法:

String encoded = encoder.encodeToString(contentBytes);

因此,要修复该错误,只需替换

// original source (indentation changed)
if (authorization != null) {
    byte[] encodedBytes;
    encodedBytes = Base64.encode(authorization.getBytes(), 0);
    authorization = "Basic " + encodedBytes;
    hc.setRequestProperty("Authorization", authorization);
}

// Fixed usage of Base64
if (authorization != null) {
    authorization = "Basic " + Base64.getEncoder().encodeToString(authorization.getBytes());
    hc.setRequestProperty("Authorization", authorization);
}