Search code examples
javamendeley

Not able to retrieve Data from Mendeley by using OAuth2 and HTTP in Java


I had an aplication that worked fine with OAuth1 on Mendeley. Since OAth1 is no more supported I have to migrate my app to OAuth2 toget the Data.

I get the token response but I cannot request any content, the program throws a NullPointerException.

I'm testing around with this sourcecode here.

I also use Apache OLTU and the Apache HTTPClient

This is the code I try to run:

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

The Exception I get is:

Exception in thread "main" java.lang.NullPointerException

I'm now asking myself why this is happening. The CATALOG_URL is from the Mendeley webside and should return the first Page of the list that contains all public groups.

I also tried different URL from the Mendeley webside.

Could there be anything wrong with the HttpGet statement?

Does anyone have any hints?


Solution

  • You are receiving a NullPointerException because you are using a variable (apacheHttpClient) that has not been initialised. Try doing this first

    apacheHttpClient = ApacheHttpTransport.newDefaultHttpClient();