gpt4 book ai didi

java - 无法在 Java 中使用 OAuth2 和 HTTP 从 Mendeley 检索数据

转载 作者:行者123 更新时间:2023-12-02 05:44:32 25 4
gpt4 key购买 nike

我有一个应用程序在 Mendeley 上与 OAuth1 配合得很好。由于不再支持 OAth1,我必须将我的应用程序迁移到 OAuth2 才能获取数据。

我收到 token 响应,但无法请求任何内容,程序抛出 NullPointerException。

我正在使用这个源代码 here 进行测试.

我还使用 Apache OLTU 和 Apache HTTPClient

这是我尝试运行的代码:

static OAuthClientRequest request;
static OAuthClient oAuthClient;

static OAuthJSONAccessTokenResponse tokenResponse ;
static String CATALOG_URL="https://api-oauth2.mendeley.com/oapi/documents/groups?items=10";


request = OAuthClientRequest
.tokenLocation("https://api-oauth2.mendeley.com/oauth/token")
.setClientId(Client_ID)
.setClientSecret(Secret)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setScope("all")
.buildBodyMessage();

System.out.println("is set up");

oAuthClient = new OAuthClient(new URLConnectionClient());
tokenResponse = oAuthClient.accessToken( request, OAuthJSONAccessTokenResponse.class);

System.out.println("token is retrieved");

HttpGet httpGet = new HttpGet(CATALOG_URL);
httpGet.setHeader("Authorization", "Bearer " + tokenResponse.getAccessToken());

//this is where the Exception is thrown
HttpResponse httpResponse = apacheHttpClient.execute(httpGet);
//

System.out.println("this is it: "+httpResponse.toString());

String responseAsString = EntityUtils.toString(httpResponse.getEntity());
System.out.println(responseAsString);

我得到的异常是:

Exception in thread "main" java.lang.NullPointerException

我现在问自己为什么会发生这种情况。CATALOG_URL 来自 Mendeley 网站,应返回包含所有公共(public)群组的列表的第一页。

我还尝试了来自 Mendeley 网站的不同 URL。

HttpGet 语句是否有问题?

有人有任何提示吗?

最佳答案

您收到 NullPointerException,因为您使用的变量 (apacheHttpClient) 尚未初始化。首先尝试这样做

apacheHttpClient = ApacheHttpTransport.newDefaultHttpClient();

关于java - 无法在 Java 中使用 OAuth2 和 HTTP 从 Mendeley 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24219622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com