1
votes

I am trying to make a call to the Petfinder API from codename one. It requires oAuth authorization. Right now I am able to get access to the API from terminal, but I do not know how to call it from codename one which uses Java. Right now I'm able to pull data from APIs that don't need oAuth but need a key.

From terminal it looks like this:

curl -d "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}" https://api.petfinder.com/v2/oauth2/token

{"token_type": "Bearer","expires_in": 3600,"access_token": "{my access token}" }

curl -H "Authorization: Bearer {my access token}" GET https://api.petfinder.com/v2/animals?type=dog&page=2

1

1 Answers

0
votes

You can use something like this. I haven't tested it though so debugging will be required:

Rest.post("https://api.petfinder.com/v2/oauth2/token").
    queryParam("grant_type", "client_credentials").
    queryParam("client_id", clientId).
    queryParam("client_secret", clientSecret).
    fetchAsJsonMap(response -> {
    // data is already parsed to Map here
    if(response.getResponseData() != null) {
        accessToken = (String)response.getResponseData().get("access_token");

        // set the auth header for all future requests in this session
        addDefaultHeader("Authorization", "Bearer " + accessToken);
    }
});

Notice that the code assumes a static import of the CN class exists. You could also store the token into Prefrences and load it dynamically/set it globally as I did here which is the more complete example.