Java Example

NOTE: Get an APIKey.

This code will allow you to get a session, fetch account info, upload a file, and search games. From it you should be able to discern how to work with the entire TGC API.

 package playground;
 
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URLEncoder;
 import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.http.HttpEntity;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.CloseableHttpResponse;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.entity.ContentType;
 import org.apache.http.entity.mime.MultipartEntityBuilder;
 import org.apache.http.entity.mime.content.FileBody;
 import org.apache.http.entity.mime.content.StringBody;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClients;
 import org.apache.http.message.BasicNameValuePair;
 import org.apache.http.util.EntityUtils;
 import org.json.JSONException;
 import org.json.JSONObject;
 
 public class TGCJavaAPI {
 
     public static void main(String[] args) throws ClientProtocolException, IOException {
         CloseableHttpClient httpclient = HttpClients.createDefault();
         
         String sessionId = "";
         String userId = "";
         
         // Get a session
         // TODO: Replace _USER_ with your username, _PASS_ with your password, and _APIKEY_ with your API Key Id
         String session = getSession(httpclient, "_USER_", "_PASS_", "_APIKEY_");
         if (session != null){
             //System.out.println(session); //Prints out full response
             //Parse the results. This uses the JSON.org library
             try {
                 JSONObject sessionObject = new JSONObject(session);
                 if (sessionObject.has("result")){
                     sessionId = sessionObject.getJSONObject("result").getString("id");
                     userId = sessionObject.getJSONObject("result").getString("user_id");
                 }
                 else if(sessionObject.has("error")){
                     System.out.println("Error: " + sessionObject.getJSONObject("error").getString("message"));
                     return;
                 }
             } catch (JSONException e) {
                 e.printStackTrace();
                 System.out.println("Error parsing session results.");
                 return;
             }
         }
         else {
             return;
         }
         
         String rootFolderId = "";
         
         //Fetch account info
         String account = fetchAccountInfo(httpclient, sessionId, userId);
         if (account != null){
             //System.out.println(account); //Prints out full response
             //Parse the results. This uses the JSON.org library
             try {
                 JSONObject accountObject = new JSONObject(account);
                 rootFolderId = accountObject.getJSONObject("result").getString("root_folder_id");
             } catch (JSONException e) {
                 e.printStackTrace();
                 System.out.println("Error parsing account results.");
                 return;
             }
         }
         
         //Upload a file
         // TODO: Replace _FILEPATH_ with the path to the file, and _FILENAME_ with the name for your file once uploaded to TGC
         String fileUplaod = fileUpload(httpclient, sessionId, "_FILEPATH_", "_FILENAME_", rootFolderId);
         if (fileUplaod != null){
             //System.out.println(fileUplaod); //Prints out full response
         }
         
         //Search games
         String searchResults = searchGames(httpclient, "pirate booty grab", sessionId);
         if (searchResults != null){
             //System.out.println(searchResults); //Prints out full response
         }
         
         httpclient.close();
     }
     
     private static String getSession(CloseableHttpClient httpclient, String username, String password, String apikeyid) throws ClientProtocolException, IOException {
         HttpPost httpPost = new HttpPost("https://www.thegamecrafter.com/api/session");
         List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
         nvps.add(new BasicNameValuePair("username", username));
         nvps.add(new BasicNameValuePair("password", password));
         nvps.add(new BasicNameValuePair("api_key_id", apikeyid));
         httpPost.setEntity(new UrlEncodedFormEntity(nvps));
         CloseableHttpResponse response = httpclient.execute(httpPost);
         StringBuffer content = new StringBuffer();
         
         try {
             HttpEntity entity = response.getEntity();
             InputStream is = entity.getContent();
             BufferedReader rd = new BufferedReader(new InputStreamReader(is));
             String line;
             while ((line = rd.readLine()) != null) {
                 content.append(line);
                 content.append('\r');
             }
             rd.close();
             // Ensure it is fully consumed
             EntityUtils.consume(entity);
         } finally {
             response.close();
         }
         return content.toString();
     }
 
     private static String fetchAccountInfo(CloseableHttpClient httpclient, String sessionId, String userId) throws ClientProtocolException, IOException {
         HttpGet httpGet = new HttpGet("https://www.thegamecrafter.com/api/user/" + userId + "?session_id=" + sessionId);
         CloseableHttpResponse response = httpclient.execute(httpGet);
         StringBuffer content = new StringBuffer();
         
         try {
             HttpEntity entity = response.getEntity();
             InputStream is = entity.getContent();
             BufferedReader rd = new BufferedReader(new InputStreamReader(is));
             String line;
             while ((line = rd.readLine()) != null) {
                 content.append(line);
                 content.append('\r');
             }
             rd.close();
             // Ensure it is fully consumed
             EntityUtils.consume(entity);
         } finally {
             response.close();
         }
         return content.toString();
     }
     
     private static String fileUpload(CloseableHttpClient httpclient, String sessionId, String filepath, String filename, String rootFolderId) throws ClientProtocolException, IOException {
         HttpPost httpPost = new HttpPost("https://www.thegamecrafter.com/api/file");
         File file = new File(filepath);
         if (!file.exists()){
             return "File does not exist.\r";
         }
         MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
         entityBuilder.addPart("file", new FileBody(file));
         entityBuilder.addPart("name", new StringBody(filepath, ContentType.TEXT_PLAIN));
         entityBuilder.addPart("folder_id", new StringBody(rootFolderId, ContentType.TEXT_PLAIN));
         entityBuilder.addPart("session_id", new StringBody(sessionId, ContentType.TEXT_PLAIN));
         HttpEntity entity = entityBuilder.build();
         httpPost.setEntity(entity);
         CloseableHttpResponse response = httpclient.execute(httpPost);
         StringBuffer content = new StringBuffer();
         
         try {
             HttpEntity entity2 = response.getEntity();
             InputStream is = entity2.getContent();
             BufferedReader rd = new BufferedReader(new InputStreamReader(is));
             String line;
             while ((line = rd.readLine()) != null) {
                 content.append(line);
                 content.append('\r');
             }
             rd.close();
             // Ensure it is fully consumed
             EntityUtils.consume(entity2);
         } finally {
             response.close();
         }
         return content.toString();
     }
     
     private static String searchGames(CloseableHttpClient httpclient, String query, String sessionId) throws ClientProtocolException, IOException {
         HttpGet httpGet = new HttpGet("https://www.thegamecrafter.com/api/game?q=" + URLEncoder.encode(query, "UTF-8") + "&_sort_by=Relevance" + (sessionId != null ? "&session_id=" + sessionId : ""));
         CloseableHttpResponse response = httpclient.execute(httpGet);
         StringBuffer content = new StringBuffer();
         
         try {
             HttpEntity entity = response.getEntity();
             InputStream is = entity.getContent();
             BufferedReader rd = new BufferedReader(new InputStreamReader(is));
             String line;
             while ((line = rd.readLine()) != null) {
                 content.append(line);
                 content.append('\r');
             }
             rd.close();
             // Ensure it is fully consumed
             EntityUtils.consume(entity);
         } finally {
             response.close();
         }
         return content.toString();
     }
 }
^ Back to Top ^