Java Code Examples for com.badlogic.gdx.Net#HttpRequest

The following examples show how to use com.badlogic.gdx.Net#HttpRequest . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
/**
 * Use careful! It resets your event to 0. Needed for first time initialization.
 *
 * @param eventId
 */
public void initializeOrResetEventKey(String eventId) {
    if (!initialized) {
        Gdx.app.error(GAMESERVICE_ID, "Cannot submit event: set app ID via initialize() first");
        return;
    }
    if (eventKeyPrefix == null) {
        Gdx.app.log(GAMESERVICE_ID, "No event key prefix provided.");
        return;
    }

    // no user name or token added! We want to use the global storage.
    // http://gamejolt.com/api/doc/game/data-store/set
    Net.HttpRequest http = buildStoreDataRequest(eventKeyPrefix + eventId, true, "0");

    if (http != null)
        Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

}
 
Example 2
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
protected Net.HttpRequest buildRequest(String component, Map<String, String> params) {
    String request = GJ_GATEWAY + component;
    request += HttpParametersUtils.convertHttpParameters(params);

    /* Generate signature */
    final String signature;
    try {
        signature = md5(request + gjAppPrivateKey);
    } catch (Exception e) {
        /* Do not leak 'gamePrivateKey' in log */
        Gdx.app.error(GAMESERVICE_ID, "Cannot honor request: " + request, e);
        return null;
    }
    /* Append signature */
    String complete = request;
    complete += "&";
    complete += "signature";
    complete += "=";
    complete += signature;

    final Net.HttpRequest http = new Net.HttpRequest();
    http.setMethod(Net.HttpMethods.GET);
    http.setUrl(complete);

    return http;
}
 
Example 3
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
/**
 * content must be without special chars ampersand or question mark - use Base64 when not sure!
 */
protected Net.HttpRequest buildStoreDataRequest(String dataKey, boolean globalKey, String content) {
    Map<String, String> params = new HashMap<String, String>();

    if (globalKey)
        params.put("game_id", gjAppId);
    else
        addGameIDUserNameUserToken(params);
    params.put("key", dataKey);

    final Net.HttpRequest http = buildJsonRequest("data-store/set/", params);
    if (http == null)
        return null;

    http.setMethod(Net.HttpMethods.POST);
    http.setHeader("Content-Type", "application/x-www-form-urlencoded");
    http.setContent("data=" + content);

    return http;
}
 
Example 4
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
protected void sendOpenSessionEvent() {
    if (!isSessionActive())
        return;

    Map<String, String> params = new HashMap<String, String>();
    addGameIDUserNameUserToken(params);

    final Net.HttpRequest http = buildJsonRequest("sessions/open/", params);

    if (http != null)
        Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

    pingTask = Timer.schedule(new Timer.Task() {
        @Override
        public void run() {
            sendKeepSessionOpenEvent();
        }
    }, GJ_PING_INTERVAL, GJ_PING_INTERVAL);

}
 
Example 5
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
/**
 * this can be used instead of loadFileFromDrive/downloadFileFromDrive... but it does not work on Firefox
 * Firefox does not follow a redirect that is given back to the real download url
 * @param driveFileId
 * @param responseListener
 */
protected void loadFileFromDriveV3(String driveFileId, final ILoadGameStateResponseListener responseListener) {
    Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
    httpRequest.setUrl("https://content.googleapis.com/drive/v3/files/" + driveFileId + "?alt=media");
    httpRequest.setHeader("Authorization", "Bearer " + oAuthToken);
    Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            byte[] result = httpResponse.getResultAsString().getBytes();
            responseListener.gsGameStateLoaded(result);
        }

        @Override
        public void failed(Throwable t) {
            responseListener.gsGameStateLoaded(null);
        }

        @Override
        public void cancelled() {
            responseListener.gsGameStateLoaded(null);
        }
    });
}
 
Example 6
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
protected void downloadFileFromDrive(String url, final ILoadGameStateResponseListener responseListener) {
    Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
    httpRequest.setUrl(url);
    httpRequest.setHeader("Authorization", "Bearer " + oAuthToken);
    Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            byte[] result = httpResponse.getResultAsString().getBytes();
            responseListener.gsGameStateLoaded(result);
        }

        @Override
        public void failed(Throwable t) {
            responseListener.gsGameStateLoaded(null);
        }

        @Override
        public void cancelled() {
            responseListener.gsGameStateLoaded(null);
        }
    });
}
 
Example 7
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
@Override
public boolean submitEvent(String eventId, int increment) {

    if (!initialized) {
        Gdx.app.error(GAMESERVICE_ID, "Cannot submit event: set app ID via initialize() first");
        return false;
    }
    if (eventKeyPrefix == null) {
        Gdx.app.log(GAMESERVICE_ID, "No event logged - no event key prefix provided.");
        return false;
    }

    Map<String, String> params = new HashMap<String, String>();
    // no user name or token added! We want to use the global storage.
    // http://gamejolt.com/api/doc/game/data-store/update
    params.put("game_id", gjAppId);
    params.put("key", eventKeyPrefix + eventId);
    params.put("value", Integer.toString(increment));
    params.put("operation", "add");

    final Net.HttpRequest http = buildJsonRequest("data-store/update/", params);
    if (http == null)
        return false;

    Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

    return true;
}
 
Example 8
Source File: KongClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
/**
 * override this method for tunneling through own server or other needs
 */
protected Net.HttpRequest buildQueryStatRequest(Integer statId, boolean playerRelated) {
    String url = "https://api.kongregate.com/api/high_scores/" +
            (playerRelated && isSessionActive() ? "friends/" + statId.toString() + "/" + Integer.toString(getUserId())
                    : "https://api.kongregate.com/api/high_scores/lifetime/" + statId.toString())
            + ".json";

    Net.HttpRequest http = new Net.HttpRequest();
    http.setMethod(Net.HttpMethods.GET);
    http.setUrl(url);

    return http;
}
 
Example 9
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
@Override
public boolean unlockAchievement(String achievementId) {
    if (trophyMapper == null) {
        Gdx.app.log(GAMESERVICE_ID, "Cannot unlock achievement: No mapper for trophy ids provided.");
        return false;
    }

    if (!isSessionActive())
        return false;

    Integer trophyId = trophyMapper.mapToGsId(achievementId);

    // no board available or not connected
    if (trophyId == null)
        return false;

    Map<String, String> params = new HashMap<String, String>();
    addGameIDUserNameUserToken(params);
    params.put("trophy_id", String.valueOf(trophyId));

    final Net.HttpRequest http = buildJsonRequest("trophies/add-achieved/", params);
    if (http == null)
        return false;

    Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

    return true;
}
 
Example 10
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
/**
 * Load data is done with dump format
 */
protected Net.HttpRequest buildLoadDataRequest(String dataKey, boolean globalKey) {
    Map<String, String> params = new HashMap<String, String>();

    if (globalKey)
        params.put("game_id", gjAppId);
    else
        addGameIDUserNameUserToken(params);
    params.put("key", dataKey);

    final Net.HttpRequest http = buildRequest("data-store/?format=dump&", params);

    return http;

}
 
Example 11
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
@Override
public boolean submitToLeaderboard(String leaderboardId, long score, String tag) {
    //GameJolt allows submitting scores without an open session.
    //Enable it by setting guest name.
    //see http://gamejolt.com/api/doc/game/scores/add

    if (!initialized) {
        Gdx.app.error(GAMESERVICE_ID, "Cannot post score: set app ID via initialize()");
        return false;
    }
    if (scoreTableMapper == null) {
        Gdx.app.log(GAMESERVICE_ID, "Cannot post score: No mapper for score table ids provided.");
        return false;
    }

    Integer boardId = scoreTableMapper.mapToGsId(leaderboardId);

    // no board available
    if (boardId == null)
        return false;

    Map<String, String> params = new HashMap<String, String>();

    if (isSessionActive())
        addGameIDUserNameUserToken(params);
    else if (guestName != null) {
        params.put("game_id", gjAppId);
        params.put("guest", guestName);
    } else {
        Gdx.app.log(GAMESERVICE_ID, "Cannot post to scoreboard. No guest name and no user given.");
        return false;
    }
    params.put("score", String.valueOf(score));
    params.put("sort", String.valueOf(score));
    if (tag != null)
        params.put("extra_data", tag);
    params.put("table_id", boardId.toString());

    final Net.HttpRequest http = buildJsonRequest("scores/add/", params);
    if (http == null)
        return false;

    Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

    return true;
}
 
Example 12
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
@Override
public void saveGameState(String fileId, byte[] gameState, long progressValue,
                          final ISaveGameStateResponseListener listener) {
    if (!isSessionActive()) {
        if (listener != null)
            listener.onGameStateSaved(false, "NOT_CONNECTED");
        return;
    }

    //TODO progressValue is saved for future use, but should be checked before overwriting existing values

    Net.HttpRequest http = buildStoreDataRequest(fileId, false,
            Long.toString(progressValue) + "\n" + new String(Base64Coder.encode(gameState)));

    Gdx.net.sendHttpRequest(http, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            String json = httpResponse.getResultAsString();
            boolean success = parseSuccessFromResponse(json);

            if (!success)
                Gdx.app.error(GAMESERVICE_ID, "Error saving gamestate: " + json);

            if (listener != null)
                listener.onGameStateSaved(success, null);
        }

        @Override
        public void failed(Throwable t) {
            Gdx.app.error(GAMESERVICE_ID, "Error saving gamestate", t);
            if (listener != null)
                listener.onGameStateSaved(false, null);
        }

        @Override
        public void cancelled() {
            Gdx.app.error(GAMESERVICE_ID, "Error saving gamestate: Cancelled");
            if (listener != null)
                listener.onGameStateSaved(false, null);
        }
    });
}
 
Example 13
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
@Override
public boolean deleteGameState(String fileId, final ISaveGameStateResponseListener successListener) {
    if (!isSessionActive())
        return false;

    Map<String, String> params = new HashMap<String, String>();

    addGameIDUserNameUserToken(params);
    params.put("key", fileId);

    final Net.HttpRequest http = buildJsonRequest("data-store/remove/", params);
    if (http == null)
        return false;

    Gdx.net.sendHttpRequest(http, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            String json = httpResponse.getResultAsString();
            boolean success = parseSuccessFromResponse(json);

            // just log, no error because deleting a nonexistant gamestate fails but is no error
            if (!success)
                Gdx.app.log(GAMESERVICE_ID, "Failed to delete gamestate: " + json);

            if (successListener != null)
                successListener.onGameStateSaved(success, null);
        }

        @Override
        public void failed(Throwable t) {
            Gdx.app.error(GAMESERVICE_ID, "Error deleting gamestate", t);
            if (successListener != null)
                successListener.onGameStateSaved(false, null);
        }

        @Override
        public void cancelled() {
            Gdx.app.error(GAMESERVICE_ID, "Error deleting gamestate: Cancelled");
            if (successListener != null)
                successListener.onGameStateSaved(false, null);
        }
    });

    return true;
}
 
Example 14
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
@Override
public void loadGameState(String fileId, final ILoadGameStateResponseListener listener) {
    if (!isSessionActive()) {
        listener.gsGameStateLoaded(null);
        return;
    }

    Net.HttpRequest http = buildLoadDataRequest(fileId, false);

    Gdx.net.sendHttpRequest(http, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            String response = httpResponse.getResultAsString();

            if (response == null || !response.startsWith("SUCCESS")) {
                // just log, no error because loading a nonexistant gamestate fails but is no error
                Gdx.app.log(GAMESERVICE_ID, "Gamestate load failed: " + response);
                listener.gsGameStateLoaded(null);
            } else {
                // indexOf is twice to cut first two lines. First one is success message,
                // second one is progressValue
                byte[] gs = Base64Coder.decode(response.substring(
                        response.indexOf('\n', response.indexOf('\n') + 1) + 1));
                listener.gsGameStateLoaded(gs);
            }
        }

        @Override
        public void failed(Throwable t) {
            Gdx.app.error(GAMESERVICE_ID, "Gamestate load failed", t);
            listener.gsGameStateLoaded(null);
        }

        @Override
        public void cancelled() {
            Gdx.app.error(GAMESERVICE_ID, "Gamestate load cancelled");

            listener.gsGameStateLoaded(null);
        }
    });
}
 
Example 15
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
protected /* @Nullable */ Net.HttpRequest buildJsonRequest(String component, Map<String, String> params) {
    component = component + "?format=json&";
    return buildRequest(component, params);
}
 
Example 16
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 4 votes vote down vote up
protected void saveFileToDrive(String fileName, String driveFileId, byte[] gameState, final ISaveGameStateResponseListener success) {
    String request = "--" + CONTENT_BOUNDARY + "\n" +
            "Content-Type: application/json; charset=UTF-8\n" +
            "\n" +
            "{\"name\": \"" + fileName + "\", \"parents\": [\"appDataFolder\"]}\n" +
            "\n" +
            "--" + CONTENT_BOUNDARY + "\n" +
            "Content-Type: application/octet-stream\n" +
            "\n" + new String(gameState) +
            "\n--" + CONTENT_BOUNDARY + "--";

    Net.HttpRequest httpRequest;
    if (driveFileId == null) {
        // create new file
        httpRequest = new Net.HttpRequest(Net.HttpMethods.POST);
        httpRequest.setUrl("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");
    } else {
        //v3 needs PATCH and PATCH is not supported by libgdx, so use v2 and PUT
        httpRequest = new Net.HttpRequest(Net.HttpMethods.PUT);
        httpRequest.setUrl("https://www.googleapis.com/upload/drive/v2/files/" + driveFileId + "?uploadType=multipart");
    }
    httpRequest.setHeader("Authorization", "Bearer " + oAuthToken);
    httpRequest.setHeader("Content-Type", "multipart/related; boundary=" + CONTENT_BOUNDARY);
    //httpRequest.setHeader("Content-Length", String.valueOf(request.length()));
    httpRequest.setContent(request);
    Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            if (success != null)
                success.onGameStateSaved(true, null);
        }

        @Override
        public void failed(Throwable t) {
            if (success != null)
                success.onGameStateSaved(false, t.getMessage());
        }

        @Override
        public void cancelled() {
            if (success != null)
                success.onGameStateSaved(true, "CANCELLED");
        }
    });
}
 
Example 17
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 3 votes vote down vote up
protected void sendKeepSessionOpenEvent() {
    if (!isSessionActive())
        return;

    Map<String, String> params = new HashMap<String, String>();
    addGameIDUserNameUserToken(params);

    final Net.HttpRequest http = buildJsonRequest("sessions/ping/", params);

    if (http != null)
        Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

}
 
Example 18
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 3 votes vote down vote up
protected void sendCloseSessionEvent() {
    if (!isSessionActive())
        return;

    Map<String, String> params = new HashMap<String, String>();
    addGameIDUserNameUserToken(params);

    final Net.HttpRequest http = buildJsonRequest("sessions/close/", params);

    if (http != null)
        Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

}