Guild Wars 2 Account API Usage in Android

1 August 2015

Simple code snippet, used for retrieving a users account data, using the Guild Wars 2 API Version 2. Hopefully, this code will help others to overcome similar problems which I was facing while learning how to program in Android.

First thing you will need is the JSONFunctions.java class:

import android.content.Context;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JSONFunctions {

    static JSONObject jObj;
    static JSONArray jArray;

    protected static String readResource (Context ctx, String filename) throws IOException {

        StringBuilder sb = new StringBuilder();
        BufferedReader input = new BufferedReader(new InputStreamReader(ctx.getAssets().open(filename), "utf-8"), 8192);

        String currLine;
        while ((currLine = input.readLine()) != null) {
            sb.append(currLine);
        }
        input.close();

        return sb.toString();
    }

    public static JSONArray getJSONFromResource (Context ctx, String filename) throws IOException {
        try {
            String json = readResource(ctx, filename);
            jArray = new JSONArray(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jArray;
    }

    protected static String readURL (String url) throws IOException {
        StringBuilder sb = new StringBuilder();

        URL requestUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"), 8192);

            String line;
            while ((line = input.readLine()) != null) {
                sb.append(line);
            }

            input.close();
        }

        return sb.toString();
    }

    public static JSONObject getJSONFromURL (String url) throws IOException {
        try {
            String json = readURL(url);
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jObj;
    }

    public static String HTTPGetFromKey (String apikey) throws IOException {

        StringBuilder sb = new StringBuilder();

        URL requestUrl = new URL("https://api.guildwars2.com/v2/account");
        HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
        conn.addRequestProperty("Authorization", "Bearer " + apikey);
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod("GET");
        conn.connect();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"), 8192);
            String line;
            while ((line = input.readLine()) != null) {
                sb.append(line);
            }
            input.close();
            conn.disconnect();
        }

        return sb.toString();
    }

    public static JSONObject getJSONFromUserKey (String key) throws IOException {
        try {
            String json = HTTPGetFromKey(key);
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jObj;
    }
}

 

Next, we need the UserInfo.java class (this will also save all the clients guild names):

import android.util.SparseArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

public class UserInfo {

    static String apiKey;
    static String userID;
    static String accountName;
    static int world;
    static int guildCount;
    static SparseArray  guildIDs;
    static SparseArray  guildNames;
    static SparseArray  guildTag;
    static String acctCreated;

    public static void init (String clientKey)
    {
        try {
            JSONObject jUser = JSONFunctions.getJSONFromUserKey (clientKey);
            apiKey = clientKey;
            userID = jUser.getString("id");
            accountName = jUser.getString("name");
            world = jUser.getInt("world");
            JSONArray jGuilds = jUser.getJSONArray("guilds");
            JSONObject jGuildInfo;
            guildCount = jGuilds.length ();
            String guildID;

            if (guildCount > 0) {
                guildIDs = new SparseArray<>();
                guildNames = new SparseArray<>();
                guildTag = new SparseArray<>();
                for (int i=0; i < guildCount; i++) {
                    guildID = jGuilds.getString(i);
                    guildIDs.put(i,guildID);
                    // This also retrieves the clents guild names
                    jGuildInfo = JSONFunctions.getJSONFromURL("https://api.guildwars2.com/v1/guild_details.json?guild_id=" + guildID);
                    guildNames.put (i, jGuildInfo.getString("guild_name"));
                    guildTag.put (i,jGuildInfo.getString("tag"));
                }
            }

            acctCreated = jUser.getString ("created");
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
    }
}

To get a users account info, all you need to do is call:

UserInfo.init(apiKey);

This will return the JSONObject of the current users account, from their personal API-Key.

Note: You can create an API-Key on the official Guild Wars 2 site. Read up more about the return JSONObject format on the GW2 official wiki.

I hope this helps out anyone new to Android and not familiar on the HTTP protocol.