Mendeley的Oauth 2与Java

时间:2014-05-08 14:48:09

标签: java apache oauth oauth-2.0 mendeley

我需要在Java中使用Mendeley创建一个应用程序。但我对oauth2的共存存在问题。

我使用Apache Oltu,但如果你知道另一个更好的选择,请告诉我。

我有这个:

OAuthClientRequest request = OAuthClientRequest
                .tokenLocation("https://api-oauth2.mendeley.com/oauth/token")
                .setGrantType(GrantType.AUTHORIZATION_CODE)
                .setClientId(CLIENT_ID)
                .setClientSecret(CLIENTE_SECRET)
                .setRedirectURI(REDIRECT_URI)
                .setCode("code")
                .setScope("all")
                .buildQueryMessage();

    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

    GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request, GitHubTokenResponse.class);

    String accessToken = oAuthResponse.getAccessToken();
    String expiresIn = oAuthResponse.getExpiresIn().toString();

    System.out.println("ACCESS TOKEN: " + accessToken);
    System.out.println("EXPIRES IN  : " + expiresIn);

但这会产生此异常:

Exception in thread "main" OAuthProblemException{error='invalid_request', description='Missing parameters: access_token', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
    at org.apache.oltu.oauth2.common.exception.OAuthProblemException.error(OAuthProblemException.java:59).......

有什么想法吗?我再说一遍,如果你知道另一种选择或解决方案,请帮助我。

非常感谢。

1 个答案:

答案 0 :(得分:1)

我们的网站http://apidocs.mendeley.com/home/authentication

上有一些文档

我使用带有Apache HTTP Client库的Apache Oltu库将一个更完整的示例放在一起。这使用匿名访问令牌。

编辑

OAuthClientRequest request = OAuthClientRequest
            .tokenLocation(TOKEN_URL)
            .setClientId(TRUSTED_CLIENT_ID)
            .setClientSecret(TRUSTED_SECRET)
            .setGrantType(GrantType.CLIENT_CREDENTIALS)
            .setScope("all")
            .buildBodyMessage();

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

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

    assertThat(httpResponse.getStatusLine().getStatusCode()).isEqualTo(200);

    String responseAsString = EntityUtils.toString(httpResponse.getEntity());

    ObjectMapper mapper = new ObjectMapper();
    Document document = mapper.readValue(responseAsString, Document.class);
    assertThat(document.getTitle()).isEqualTo("Identifying and recording user actions to enable automatic online assessment");