Java 类com.badlogic.gdx.Net 实例源码

项目:gdx-gamesvcs    文件:GpgsClient.java   
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);
        }
    });
}
项目:gdx-gamesvcs    文件:GpgsClient.java   
/**
 * 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);
        }
    });
}
项目:gdx-gamesvcs    文件:GameJoltClient.java   
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);

}
项目:gdx-gamesvcs    文件:GameJoltClient.java   
/**
 * 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());

}
项目:gdx-gamesvcs    文件:GameJoltClient.java   
/**
 * 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;
}
项目:gdx-gamesvcs    文件:GameJoltClient.java   
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;
}
项目:enklave    文件:RequestTokenSocket.java   
public static void getTicket(final WebSocketLocal webSocket){
    final JSONObject[] finalResult = new JSONObject[1];
    String accesToken = Gdx.app.getPreferences("informationLog").getString("accesstoken");
    HttpRequestBuilder buider = new HttpRequestBuilder();
    Net.HttpRequest request = buider.newRequest().url(api_url + d_login).method(Net.HttpMethods.POST).build();
    request.setHeader("Authorization", "Bearer " + accesToken);
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            String r = httpResponse.getResultAsString();
            webSocket.connectWebSocket(new JSONObject(r));
            Gdx.app.log("response", "ticket "+r);
        }

        @Override
        public void failed(Throwable t) {
            webSocket.connectWebSocket(new JSONObject());
        }

        @Override
        public void cancelled() {
            webSocket.connectWebSocket(new JSONObject());
        }
    });
}
项目:enklave    文件:NearbyEnklave.java   
public void makeRequestEnklave(){
    Preferences pref = Gdx.app.getPreferences("informationLog");
    String acces = pref.getString("accesstoken");
    HttpRequestBuilder builder = new HttpRequestBuilder();
    Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.GET).url(url + enkNearby).build();
    request.setHeader("Authorization", "Bearer " + acces);
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            String response = httpResponse.getResultAsString();
            JSONArray jsonArray = new JSONArray(response);
            ListEnklaves.getInstance().setListEnklave(jsonArray);
            Gdx.app.log("response enklave : " + httpResponse.getStatus().getStatusCode(), " message " +response);
        }

        @Override
        public void failed(Throwable t) {
            Gdx.app.log("response : " + t.getMessage(), "fdg " + t.getLocalizedMessage());
        }

        @Override
        public void cancelled() {
            Gdx.app.log("response ","cancelled");
        }
    });
}
项目:cachebox3.0    文件:NetUtils.java   
public static Object postAndWait(final ResultType type, final Net.HttpRequest request, final ICancel icancel) {
log.debug("Send Post request");
final AtomicBoolean WAIT = new AtomicBoolean(true);
final Object[] result = new Object[1];
if(icancel!=null){
    CB.postAsync(new Runnable() {
        @Override
        public void run() {
            while (WAIT.get()) {
                if (icancel.cancel()) {
                    Gdx.net.cancelHttpRequest(request);
                }
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

final AtomicBoolean isRedirection = new AtomicBoolean(false);
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
项目:cachebox3.0    文件:GCVote.java   
public static Boolean sendVotes(String User, String password, int vote, String url, String waypoint, ICancel icancel) {
    String guid = url.substring(url.indexOf("guid=") + 5).trim();

    String data = "userName=" + User + "&password=" + password + "&voteUser=" + String.valueOf(vote / 100.0) + "&cacheId=" + guid + "&waypoint=" + waypoint;

    try {
        Net.HttpRequest httpPost = new Net.HttpRequest(Net.HttpMethods.POST);
        httpPost.setUrl("http://gcvote.de/getVotes.php");
        httpPost.setTimeOut(Config.socket_timeout.getValue());
        httpPost.setContent(data);


        String responseString = (String) NetUtils.postAndWait(NetUtils.ResultType.STRING, httpPost, icancel);

        return responseString.equals("OK\n");

    } catch (Exception ex) {
        return false;
    }
}
项目:submarine    文件:StatsReporter.java   
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
    try {
        handleResponse(httpResponse.getResultAsString());
        if (statsReporterResponseListener != null) {
            statsReporterResponseListener.succeed(responseVO);
        }
    } catch (Error error) {
        Gdx.app.error(TAG, error.getMessage());
        if (statsReporterResponseListener != null) {
            statsReporterResponseListener.failed(error);
        }
    } catch (SerializationException e) {
        e.printStackTrace();
        if (statsReporterResponseListener != null) {
            statsReporterResponseListener.failed(e);
        }
    }
}
项目:NerdShooter    文件:NetworkHandle.java   
protected void sendRequest(String method, Map<String, String> params, final NetworkListener listener){
    HttpRequest httpPost = new HttpRequest(HttpMethods.POST);
    httpPost.setUrl(website + method + ".php");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPost.setContent(HttpParametersUtils.convertHttpParameters(params));

    Gdx.net.sendHttpRequest (httpPost, new HttpResponseListener() {
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            String responce = new String(httpResponse.getResult());
            String dat = decrypt(responce, ENC_KEY);
            listener.finished(dat);
            listener.length(dat.getBytes().length);
        }

        public void failed(Throwable t) {
            listener.failed(t);
        }

        public void cancelled(){

        }
    });
}
项目:Cardshifter    文件:CardshifterNonGWTClient.java   
public CardshifterNonGWTClient(CardshifterPlatform platform, String host, int port,
     CardshifterMessageHandler handler, LoginMessage loginMessage) {
    socket = Gdx.net.newClientSocket(Net.Protocol.TCP, host, port, new SocketHints());
    output = socket.getOutputStream();
    input = socket.getInputStream();
    transformer = new ByteTransformer(new GdxLogger(), new GdxReflection());
    this.handler = handler;
    try {
        output.write("{ \"command\": \"serial\", \"type\": \"1\" }".getBytes());
        output.flush();
        Gdx.app.log("Client", "Sent serial type");
        platform.setupLogging();
        send(loginMessage);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    new Thread(this).start();
}
项目:LibGDXServer    文件:ClientSocket.java   
public ClientSocket(Net.Protocol protocol, String host, int port, SocketHints hints) {
    try {
        // create the socket
        socket = new java.net.Socket();
        applyHints(hints);  // better to call BEFORE socket is connected!

        // and connect...
        InetSocketAddress address = new InetSocketAddress(host, port);
        if (hints != null) {
            socket.connect(address, hints.connectTimeout);
        } else {
            socket.connect(address);
        }
    } catch (Exception e) {
        throw new GdxRuntimeException("Error making a socket connection to " + host + ":" + port, e);
    }
}
项目:gdx-gamesvcs    文件:KongClient.java   
/**
 * 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;
}
项目:gdx-gamesvcs    文件:GameJoltClient.java   
@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;
}
项目:gdx-gamesvcs    文件:GameJoltClient.java   
@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;
}
项目:gdx-gamesvcs    文件:GameJoltClient.java   
/**
 * 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;

}
项目:enklave    文件:SendFaction.java   
public void sendMessage(String message){
    final Preferences pref = Gdx.app.getPreferences("informationLog");
    String acces = pref.getString("accesstoken");
    JSONObject json = new JSONObject();
    json.accumulate("txt",message);
    HttpRequestBuilder builder = new HttpRequestBuilder();
    Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + join).build();
    request.setHeader("Authorization", "Bearer " + acces);
    request.setHeader("Content-type", "application/json");
    request.setContent(json.toString());
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            //Gdx.app.log("response :"+httpResponse.getStatus().getStatusCode(),"message "+httpResponse.getResultAsString());
        }

        @Override
        public void failed(Throwable t) {
            //Gdx.app.log("response :","failed "+t);
        }

        @Override
        public void cancelled() {
            //Gdx.app.log("response :","cancel ");
        }
    });
}
项目:enklave    文件:SendLocation.java   
public void sendMessage(String message){
        final Preferences pref = Gdx.app.getPreferences("informationLog");
        String acces = pref.getString("accesstoken");
        JSONObject json = new JSONObject();
        json.accumulate("txt",message);
        HttpRequestBuilder builder = new HttpRequestBuilder();
        Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + join).build();
        request.setHeader("Authorization", "Bearer " + acces);
        request.setHeader("Content-type", "application/json");
        request.setContent(json.toString());
        Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
            @Override
            public void handleHttpResponse(Net.HttpResponse httpResponse) {
//                Gdx.app.log("response :"+httpResponse.getStatus().getStatusCode(),"message "+httpResponse.getResultAsString());
            }

            @Override
            public void failed(Throwable t) {
                //Gdx.app.log("response :","failed "+t);
            }

            @Override
            public void cancelled() {
                //Gdx.app.log("response :","cancel ");
            }
        });
    }
项目:enklave    文件:JoinFaction.java   
public void makeRequest(int id){
    final Preferences pref = Gdx.app.getPreferences("informationLog");
    String acces = pref.getString("accesstoken");
    JSONObject json = new JSONObject();
    json.accumulate("faction_id",id);
    HttpRequestBuilder builder = new HttpRequestBuilder();
    Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + join).build();
    request.setHeader("Authorization", "Bearer " + acces);
    request.setHeader("Content-type", "application/json");
    request.setContent(json.toString());
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            //Gdx.app.log("response :","message "+httpResponse.getResultAsString());
        }

        @Override
        public void failed(Throwable t) {
            //Gdx.app.log("response :","failed ");
        }

        @Override
        public void cancelled() {
            //Gdx.app.log("response :","cancel ");
        }
    });
}
项目:enklave    文件:HitEnklave.java   
public void makeRequest(int id, final ScreenCombat screenCombat){
    final Preferences pref = Gdx.app.getPreferences("informationLog");
    final String acces = pref.getString("accesstoken");
    JSONObject parameters = new JSONObject();
    parameters.accumulate("enklave_combat_id",id);
    HttpRequestBuilder builder = new HttpRequestBuilder();
    Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + prof).build();
    request.setHeader("Authorization", "Bearer " + acces);
    request.setHeader("Content-type", "application/json");
    request.setContent(parameters.toString());
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            screenCombat.showCover();
            Gdx.app.log("raspuns hit Enklave cod :"+httpResponse.getStatus().getStatusCode()," message : "+httpResponse.getResultAsString());
        }

        @Override
        public void failed(Throwable t) {

        }

        @Override
        public void cancelled() {

        }
    });
}
项目:enklave    文件:StartCombat.java   
public void makeRequest(int id, final ScreenCombat screenCombat){
    final Preferences pref = Gdx.app.getPreferences("informationLog");
    final String acces = pref.getString("accesstoken");
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("enklave_id", id);
    HttpRequestBuilder builder = new HttpRequestBuilder();
    Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + prof).build();
    request.setHeader("Authorization", "Bearer " + acces);
    request.setHeader("Content-type", "application/json");
    request.setContent(jsonObject.toString());
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            String res = httpResponse.getResultAsString();
            Gdx.app.log("raspuns start code "+httpResponse.getStatus().getStatusCode(),"rasp mess: "+res);
            if(httpResponse.getStatus().getStatusCode()<300){
                JSONObject j = new JSONObject(res);
                informationProfile.getDateUserGame().setEnklaveCombatId(j.getInt("enklave_combatant_id"));
                InformationEnklave.getInstance().setCombatId(j.getInt("enklave_combat_id"));
                informationProfile.getDateUserGame().setInCombat(true);
            }else{
                JSONObject json = new JSONObject(res);
                if(json.getString("detail").contentEquals("You already joined this combat once"))
                    InformationProfile.getInstance().getDateUserGame().setEnklaveCombatId(-1);
                informationProfile.getDateUserGame().setInCombat(true);
                screenCombat.dialogExit(json.getString("detail").substring(0,20)+"\n"+json.getString("detail").substring(21));
            }
        }

        @Override
        public void failed(Throwable t) {
            Gdx.app.log("error parse data : ","err: "+t);
        }

        @Override
        public void cancelled() {

        }
    });
}
项目:enklave    文件:UnsubscribeCombat.java   
public void makeRequest(int id){
    final Preferences pref = Gdx.app.getPreferences("informationLog");
    final String acces = pref.getString("accesstoken");
    JSONObject parameters = new JSONObject();
    parameters.accumulate("enklave_id",id);
    HttpRequestBuilder builder = new HttpRequestBuilder();
    Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + prof).build();
    request.setHeader("Authorization", "Bearer " + acces);
    request.setHeader("Content-type", "application/json");
    request.setContent(parameters.toString());
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            Gdx.app.log("raspuns unsubscribe cod :"," message : "+httpResponse.getResultAsString());
        }

        @Override
        public void failed(Throwable t) {

        }

        @Override
        public void cancelled() {

        }
    });
}
项目:enklave    文件:HitUser.java   
public void makeRequest(int id, final ScreenCombat screenCombat){
    final Preferences pref = Gdx.app.getPreferences("informationLog");
    final String acces = pref.getString("accesstoken");
    JSONObject parameters = new JSONObject();
    parameters.accumulate("enklave_combatant_id",id);
    HttpRequestBuilder builder = new HttpRequestBuilder();
    Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + prof).build();
    request.setHeader("Authorization", "Bearer " + acces);
    request.setHeader("Content-type", "application/json");
    request.setContent(parameters.toString());
    Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            screenCombat.showCover();
            Gdx.app.log("raspuns hit user cod :"+httpResponse.getStatus().getStatusCode()," message : "+httpResponse.getResultAsString());
        }

        @Override
        public void failed(Throwable t) {

        }

        @Override
        public void cancelled() {

        }
    });
}
项目:enklave    文件:SubscribeCombat.java   
public void makeRequest(final int id){
        final Preferences pref = Gdx.app.getPreferences("informationLog");
        final String acces = pref.getString("accesstoken");
        JSONObject parameters = new JSONObject();
        parameters.accumulate("enklave_id",id);
        HttpRequestBuilder builder = new HttpRequestBuilder();
        Net.HttpRequest request = builder.newRequest().method(Net.HttpMethods.POST).url(url + prof).build();
        request.setHeader("Authorization", "Bearer " + acces);
        request.setHeader("Content-type", "application/json");
        request.setContent(parameters.toString());
        Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
            @Override
            public void handleHttpResponse(Net.HttpResponse httpResponse) {
//                Gdx.app.log("response "+httpResponse.getStatus().getStatusCode()," subscribe "+httpResponse.getResultAsString());
                if(httpResponse.getStatus().getStatusCode()<300){
                    new CheckStatus().makeRequest(id);
                }else{

                }
            }

            @Override
            public void failed(Throwable t) {

            }

            @Override
            public void cancelled() {

            }
        });
    }
项目:fluffybalance    文件:LeaderBoardController.java   
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
    String result = httpResponse.getResultAsString();

    Json json = new Json();

    ArrayList list = json.fromJson(ArrayList.class, result);
    Array<LeaderBoardEntry> leaderBoardEntries = new Array<LeaderBoardEntry>();

    if (list != null) {
        for (Object entry : list) {
            if (entry != null && entry instanceof JsonValue) {
                JsonValue jsonEntry = (JsonValue) entry;

                // the reflection does not seem to work on iOS
                // LeaderBoardEntry leaderBoardEntry = json.readValue(
                //    LeaderBoardEntry.class, (JsonValue)entry);
                LeaderBoardEntry leaderBoardEntry = new LeaderBoardEntry();
                try {
                    leaderBoardEntry.name = jsonEntry.getString("name");
                    leaderBoardEntry.rank = jsonEntry.getInt("rank");
                    leaderBoardEntry.score = jsonEntry.getInt("score");
                } catch (IllegalArgumentException e) {
                    Gdx.app.log(TAG, "failed to read json: " + e.toString());
                    return;
                }

                leaderBoardEntries.add(leaderBoardEntry);
            }
        }
    }

    mListener.onSuccess(leaderBoardEntries);
}
项目:fluffybalance    文件:LeaderBoardController.java   
public void addScore(AddScoreListener listener, int score, String name) {
    HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("name", name);
    parameters.put("score", "" + score);

    Net.HttpRequest httpRequest = requestBuilder.newRequest()
            .method(Net.HttpMethods.POST)
            .formEncodedContent(parameters)
            .url("https://www.fluffybalance.nl/api/1.0/score")
            .build();
    Gdx.net.sendHttpRequest(httpRequest, new AddScoreResponseListener(listener));
}
项目:cachebox3.0    文件:FileBrowserClint.java   
public boolean connect() {

        if (socket != null) {
            if (socket.isConnected())
                return true;
        }

        try {
            SocketHints hints = new SocketHints();
            socket = Gdx.net.newClientSocket(Net.Protocol.TCP, serverAddress, serverPort, hints);

            os = socket.getOutputStream();
            bos = new BufferedOutputStream(os, BUFFER_SIZE);
            dos = new DataOutputStream(bos);
            in = socket.getInputStream();
            bis = new BufferedInputStream(in, BUFFER_SIZE);
            dis = new DataInputStream(bis);

            dos.writeUTF(CONNECT);
            dos.flush();

            String response = dis.readUTF();
            log.debug("got server message: " + response);

            if (response.equals(CONNECTED)) {
                return true;
            }
        } catch (Exception e) {
            log.error("an error occured", e);
        }
        return false;
    }
项目:cachebox3.0    文件:NetUtils.java   
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
    if (httpResponse.getStatus().getStatusCode() >= 301 && httpResponse.getStatus().getStatusCode() <= 302) {
        log.debug("redirection");
        final String redirection = httpResponse.getHeader("Location");
        if (redirection != null) {
            CB.postAsync(new Runnable() {
                @Override
                public void run() {
                    isRedirection.set(true);
                    Gdx.net.cancelHttpRequest(request);
                    Net.HttpRequest httpGet = new Net.HttpRequest(request.getMethod());
                    httpGet.setUrl(redirection);
                    result[0] = postAndWait(type, httpGet, icancel);
                    WAIT.set(false);
                }
            });
        }
        return;
    }

    log.debug("Handle Response");
    final AtomicBoolean HANDEL_WAIT = new AtomicBoolean(true);
    switch (type) {

        case STRING:
            result[0] = httpResponse.getResultAsString();
            HANDEL_WAIT.set(false);
            break;
        case STREAM:
            result[0] = new StreamHandleObject() {
项目:cachebox3.0    文件:GetApiLimits.java   
public static int getLimit() {
    String URL = Config.StagingAPI.getValue() ? STAGING_GS_LIVE_URL : GS_LIVE_URL;

    Net.HttpRequest httpGet = new Net.HttpRequest(Net.HttpMethods.GET);
    httpGet.setUrl(URL + "GetAPILimits?AccessToken=" + getAccessToken(true) + "&format=json");

    NetUtils.StreamHandleObject result = (NetUtils.StreamHandleObject) NetUtils.postAndWait(NetUtils.ResultType.STREAM, httpGet, null);
    //  for debug: String result = (String) NetUtils.postAndWait(NetUtils.ResultType.STRING, httpGet, null);

    ApiLimitParser parser = new ApiLimitParser();
    int parseResult = parser.parseCallsPerMinute(result.stream);
    result.handled();
    return parseResult;
}
项目:dice-heroes    文件:LocalMultiplayer.java   
public void init() {
    if (initialized)
        return;
    invitesWindow = new InvitesWindow();
    playersWindow = new InvitesWindow();
    initialized = true;
    try {
        socket = Gdx.net.newClientSocket(Net.Protocol.TCP, "localhost", 1337, new SocketHints());
    } catch (Exception e) {
        return;
    }

    new Thread(new Runnable() {
        @Override public void run() {
            final BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {
                try {
                    final String msg = r.readLine();
                    Gdx.app.postRunnable(new Runnable() {
                        @Override public void run() {
                            ClientServerMessage message = ClientServerMessage.json.fromJson(ClientServerMessage.class, msg);
                            receive(message);
                        }
                    });
                } catch (IOException ignored) {
                    System.out.println(ignored.getMessage());
                }
            }
        }
    }).start();
    sendToServer(ClientServerMessage.Type.loadPlayersToInvite);
    sendToServer(ClientServerMessage.Type.loadInvites);
}
项目:submarine    文件:StatsReporter.java   
@Override
public Void call() throws Exception {
    statsReporterVO = crateStatsRequestVO();
    try {
        Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
        httpRequest.setUrl(url);
        httpRequest.setContent(HttpParametersUtils.convertHttpParameters(getParameters()));
        Gdx.net.sendHttpRequest(httpRequest, new StatsReporterHttpResponseListener());
        Gdx.app.debug(TAG, "httpRequest : " + httpRequest.getUrl());
    } catch (Exception e) {
        // no connection no cry
        e.printStackTrace();
    }
    return null;
}
项目:Boogie    文件:DownloadUtils.java   
public void run()
{
    Array<String> files = new Array<String>();
    files.add("boogie.hash");
    try (Scanner scanner = new Scanner(new FileInputStream(new File(".tmp/boogie.hash"))))
    {
        while (scanner.hasNext())
        {
            scanner.next();
            files.add(scanner.next());
        }

    } catch (IOException e)
    {
        e.printStackTrace();
    }

    Runnable after = new CheckDownloads(files.size);
    for (String file : files)
    {

        Net.HttpRequest get = new Net.HttpRequest(Net.HttpMethods.GET);
        get.setUrl(url + file);
        get.setTimeOut(5000);

        Gdx.net.sendHttpRequest(get, new FileDownloader(file, after));
    }

}
项目:ead    文件:GleanerSystemForTest.java   
@Override
protected Storage buildGleanerStorage() {
    LocalStorage storage = new LocalStorage(
            fileHandleForLocalStorage("test")) {

        @Override
        public void send(String data, Net.HttpResponseListener flushListener) {
            GleanerSystemForTest.this.data = data;
            super.send(data, flushListener);
        }
    };
    return storage;
}
项目:ead    文件:GleanerSystemForTest.java   
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
    flushListener.handleHttpResponse(httpResponse);
    if (listener != null) {
        listener.dataSent(data);
    }
}
项目:ead    文件:AbstractPlatform.java   
@Override
public <T> T sendHttpGetRequest(String URL, Class<T> type)
        throws IOException {
    HttpRequest httpRequest = Pools.obtain(HttpRequest.class);
    httpRequest.setMethod(Net.HttpMethods.GET);
    httpRequest.setTimeOut(TIMEOUT);
    httpRequest.setUrl(URL);
    try {
        return sendHttpRequest(httpRequest, type);
    } finally {
        Pools.free(httpRequest);
    }
}
项目:LibGDXServer    文件:ServerApplicationSocket.java   
public ServerApplicationSocket(Net.Protocol protocol, int port, ServerSocketHints hints) {
    this.protocol = protocol;

    // create the server socket
    try {
        // initialize
        server = new java.net.ServerSocket();
        if (hints != null) {
            server.setPerformancePreferences(hints.performancePrefConnectionTime,
                    hints.performancePrefLatency,
                    hints.performancePrefBandwidth);
            server.setReuseAddress(hints.reuseAddress);
            server.setSoTimeout(hints.acceptTimeout);
            server.setReceiveBufferSize(hints.receiveBufferSize);
        }

        // and bind the server...
        InetSocketAddress address = new InetSocketAddress(port);
        if (hints != null) {
            server.bind(address, hints.backlog);
        } else {
            server.bind(address);
        }
    } catch (Exception e) {
        throw new GdxRuntimeException("Cannot create a server socket at port " + port + ".", e);
    }
}
项目:gdx-gamesvcs    文件:GpgsClient.java   
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");
        }
    });
}
项目:gdx-gamesvcs    文件:GpgsClient.java   
@Override
public boolean deleteGameState(String fileId, final ISaveGameStateResponseListener success) {
    if (!enableDrive)
        throw new UnsupportedOperationException("To use game states, enable Drive API when initializing");

    if (!isSessionActive())
        return false;

    findDriveFileId(fileId, new IDoWithDriveFileId() {
        @Override
        public void doWithDriveFileId(String driveFileId) {
            if (driveFileId == null)
                success.onGameStateSaved(true, null);
            else {
                Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.DELETE);
                httpRequest.setUrl("https://www.googleapis.com/drive/v3/files/" + driveFileId);
                httpRequest.setHeader("Authorization", "Bearer " + oAuthToken);
                Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
                    @Override
                    public void handleHttpResponse(Net.HttpResponse httpResponse) {
                        if (success != null)
                            success.onGameStateSaved(true, "");
                    }

                    @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");
                    }
                });

            }
        }
    });

    return true;
}