Getting a JSON object from DigitalOcean in Java

How to get a JSON object from DigitalOcean. This uses Gson.

Getting the HTTP object.

Inputs:

url: URL to access i.e. https://api.digitalocean.com/v2/droplets/
auth_key: Authorization key from DO.

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

    private static InputStream retrieveStream(String url, String auth_key) {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);

        getRequest.addHeader("Authorization","Bearer " + auth_key);
    try {
        HttpResponse getResponse = client.execute(getRequest);  
        statusCode = getResponse.getStatusLine().getStatusCode();

        HttpEntity getResponseEntity = getResponse.getEntity();
        return getResponseEntity.getContent();
    } 
    catch (IOException e) {
        getRequest.abort();
    }
    return null;
}

Converting the response into a Java object:

        InputStream stream = retrieveStream(url, auth_key);
        Reader reader = new InputStreamReader(stream);

        Gson gson = new Gson();
        Droplets response = gson.fromJson(reader, Droplets.class);

Where Droplets.class is implemented like this and Droplet.class is implemented like this.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s