需要使用 java 打印访问令牌

Need to print access token using java

当我从邮递员那里打电话给 API 时,它 returns access-token

但是当我从 java 调用相同的 API 时它 returns status code, url 但它不会 return access token。下面是我的程序打印的 response

Response{protocol=http/1.1, code=200, message=OK, url=https://idcs-82972921e42641b1bf08128c3d93a19c.identity.c9dev2.oc9qadev.com/oauth2/v1/token}

下面是代码。

import java.io.IOException;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class NewClass {
    
    public static void main(String[] args) throws IOException {
        
        OkHttpClient client = new OkHttpClient();
        
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&scope=https://idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1");
                Request request = new Request.Builder()
                  .url("https://idcs-82972921e42641b1bf08128c3d93a19c.identity.c9dev2.oc9qadev.com/oauth2/v1/token")
                  .method("POST", body)
                  .addHeader("Content-Type", "application/x-www-form-urlencoded")
                  .addHeader("Authorization", "Basic aWRjcy1vZGEtOTQxN2Y5MzU2MGI5NGViOGEyZTJhNGM5YWFjOWEzZmYtdDBfQVBQSUQ6MjQ0YWU4ZTItNmY3MS00YWYyLWI1Y2MtOTExMDg5MGQxNDU2")
                  .build();
                Response response = client.newCall(request).execute();
            System.out.println(response);
            
    }

}

如何打印 Access token

您可以使用 System.out.println(response.body().string()); 打印整个响应字符串 现在您必须使用 POJO class 将字符串解析为 JSON 对象。从 POJO class,您可以只打印访问令牌或从 API 响应中获得的任何内容。 您可以查看 here 如何将字符串转换为 JSON 对象。