public static bool sendScoreFactorData(int clearTime, string completeStatus, int starsGrade) { if(sendEnabled){ level = GameManagerVik.nextLevel.ToString(); token = UserDatabase.token; gameID = GameManagerVik.gameID; string urlconcat = "/game" + "/" + gameID + "?auth_token=" + token + "&game[level]=" + level + "&game[completed]=" + completeStatus + "&game[cleartime]=" + clearTime + "&game[stars]=" + starsGrade; var r = new HTTP.Request ("PUT", url + urlconcat); r.Send (); while (!r.isDone) { if (r.exception != null) { Debug.Log (r.exception.ToString ()); } } if (r.exception != null) { Debug.Log (r.exception.ToString ()); } else { Debug.Log(r.response.Text); Debug.Log("Clear time analytics sent online."); return true; } } return false; }
public static void sendAnalytics(Transform player, string dataToAnalyse) { //blockmake //plankmake //death //buttonpress //jump //Viewer Cam //Move Obj token = UserDatabase.token; level = GameManagerVik.nextLevel.ToString(); gameID = GameManagerVik.gameID; xPos = player.position.x.ToString(); yPos = player.position.y.ToString(); zPos = player.position.z.ToString(); string urlconcat = "/" + dataToAnalyse + "?" + dataToAnalyse + "[game_id]=" + gameID + "&" + dataToAnalyse + "[level]=" + level + "&" + dataToAnalyse + "[x]=" + xPos + "&" + dataToAnalyse + "[y]=" + yPos + "&" + dataToAnalyse + "[z]=" + zPos + "&auth_token=" + token; var r = new HTTP.Request ("POST", url + urlconcat); r.Send (); Debug.Log("Analytics sent online."); }
public void resetNodeColor() { string nodeColors = ""; for (int i = 0; i < 225; i++) { nodeColors += 0; } Hashtable data = new Hashtable(); data.Add("Session", "1"); data.Add("NodeColorString", nodeColors); HTTP.Request theRequest = new HTTP.Request("post", uri + "users", data); theRequest.Send((request) => { Hashtable result = request.response.Object; if (result == null) { Debug.LogWarning("Could not parse JSON response!"); return; } Debug.Log(request.response.Text); }); }
public IEnumerator JoinGameCoroutine(string gameKey, QueryGameResults queryGameResults) { HTTP.Request request = new HTTP.Request( "get", _server + "/joinGame" ); request.Send(); while( !request.isDone ) { yield return null; } if( request.exception != null ) { queryGameResults( null, request.exception.ToString () ); } var responseText = request.response.Text; var endOfCommand = responseText.IndexOf (":"); var command = responseText.Substring (0, endOfCommand).Trim(); var result = responseText.Substring( endOfCommand + 1 ).Trim(); if (command == "/joinGame") { queryGameResults( null, null ); } else { queryGameResults( null, "Error: " + result ); } }
void login(string username, string point) { Debug.LogWarning (point); User user = StateGame.stateGame.getUserByLogin (username); string pass = user.getPass(); Hashtable data = new Hashtable(); data.Add( "username", username); data.Add( "password", pass ); // Collect headers for upload score string token, client, expiry, type, uuid; HTTP.Request someRequest = new HTTP.Request("post", "http://boiling-sea-3589.herokuapp.com/api/auth/sign_in", data); //HTTP.Request someRequest = new HTTP.Request( "get", "https://www.google.com"); someRequest.Send( ( request ) => { if(request.response != null) { token = request.response.GetHeader("Access-Token"); client = request.response.GetHeader("Client"); expiry = request.response.GetHeader("Expiry"); type = request.response.GetHeader("Token-Type"); uuid = request.response.GetHeader("Uid"); Debug.LogWarning(request.response.Text); Debug.LogWarning(someRequest.isDone); if (someRequest.isDone) { uploadScore(point, token, client, expiry, type, uuid); } else { NotificationCenter.DefaultCenter().PostNotification(this, "sendMessage", "User not found!!!!"); } } }); }
IEnumerator Start () { var uniwebSeconds = 0.0; var wwwSeconds = 0.0; //Warm up engines. yield return new HTTP.Request ("GET", "http://www.differentmethods.com/").Send(); yield return new WWW ("http://www.differentmethods.com/"); for (var i=0; i<10; i++) { var clock = new Stopwatch (); var req = new HTTP.Request ("GET", "http://www.differentmethods.com/"); clock.Start (); yield return req.Send (); clock.Stop (); uniwebSeconds += clock.Elapsed.TotalSeconds; } for (var i=0; i<10; i++) { var clock = new Stopwatch (); var req = new WWW ("http://www.differentmethods.com/"); clock.Start (); yield return req; clock.Stop (); wwwSeconds += clock.Elapsed.TotalSeconds; } UnityEngine.Debug.Log("UniWeb: " + (uniwebSeconds/10)); UnityEngine.Debug.Log("WWW: " + (wwwSeconds/10)); }
public IEnumerator CreateGameCoroutine(string name, string password, CreateGameResults startGameResults) { HTTP.Request request = new HTTP.Request( "get", _server + string.Format ( "/createGame?name={0}&password={1}", name, password ) ); request.Send(); while( !request.isDone ) { yield return null; } if( request.exception != null ) { startGameResults( null, request.exception.ToString () ); } var responseText = request.response.Text; var endOfCommand = responseText.IndexOf (":"); var command = responseText.Substring (0, endOfCommand).Trim(); var result = responseText.Substring( endOfCommand + 1 ).Trim(); if (command == "/createGame") { startGameResults( null, null ); } else { startGameResults( null, "Error: " + result ); } }
public void LoadMade() { made_state = state.LOADING; made.Clear(); string url = SocialManager.Instance.FIREBASE + "/challenges.json"; //?orderBy=\"time\"&limitToLast=30"; url += "?orderBy=\"facebookID\"&equalTo=\"" + SocialManager.Instance.userData.facebookID + "\""; Debug.Log("LoadMade: " + url); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { Hashtable decoded = (Hashtable)JSON.JsonDecode(request.response.Text); if (decoded == null) { Debug.LogError("server returned null or malformed response ):"); return; } foreach (DictionaryEntry json in decoded) { Hashtable jsonObj = (Hashtable)json.Value; PlayerData newData = new PlayerData(); newData.objectID = (string)json.Key; newData.facebookID = (string)jsonObj["op_facebookID"]; newData.playerName = (string)jsonObj["op_playerName"]; newData.score = (int)jsonObj["score"]; newData.score2 = (int)jsonObj["score2"]; newData.winner = (string)jsonObj["winner"]; newData.notificated = (bool)jsonObj["notificated"]; made.Add(newData); } made_state = state.READY; }); }
protected void CheckIfUserExists(string facebookID) { Debug.Log("CheckIfUserExists: " + facebookID + username); string url = SocialManager.Instance.FIREBASE + "/users.json?orderBy=\"facebookID\"&equalTo=\"" + facebookID + "\""; Debug.Log(url); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { Hashtable decoded = (Hashtable)JSON.JsonDecode(request.response.Text); if (decoded == null) { Debug.Log("no existe el user or malformed response ):"); return; } else if (decoded.Count == 0) { AddNewUser(facebookID); } else { SocialEvents.OnUserReady(username, facebookID); } }); }
public Match GetMatchForId(string id) { try{ HTTP.Request request = new HTTP.Request("get", this.baseUrl + ("matches/" + id)); request.Send(); while (!request.isDone) { } JSONObject matchesJson = new JSONObject(request.response.Text); List <JSONObject> json = matchesJson.list; if (!(json[0].str == "not_found" && json[1].str == "missing")) { Match match = new Match(); //match.Id = json[0].str; //match.Revision = json[1].str; //match.ChallengerId = json[2].str; //match.ChallengedId = json[3].str; match.ChallengerScore = (int)json[4].n; match.ChallengedScore = (int)json[5].n; //match.Winner = json[6].str; match.Seed = (int)json[7].n; return(match); } } catch (Exception e) { FbDebug.Log(e.StackTrace); } return(null); }
public void UpdatePlayerData(Player player) { try{ string jsonString; if (player.Revision != null) { jsonString = "{\"_id\":\"" + player.Id + "\",\"_rev\":\"" + player.Revision + "\",\"Name\":\"" + player.Name + "\",\"Coins\":" + player.Coins + ",\"Highscore\":" + player.Highscore + "}"; } else { jsonString = "{\"Name\":\"" + player.Name + "\",\"Coins\":" + player.Coins + ",\"Highscore\":" + player.Highscore + "}"; } HTTP.Request request = new HTTP.Request("put", this.baseUrl + "players/" + player.Id, new MemoryStream(Encoding.UTF8.GetBytes(jsonString))); request.synchronous = true; request.Send((requestObject) => { JSONObject playerJSON = new JSONObject(requestObject.response.Text); List <JSONObject> json = playerJSON.list; player.Revision = json[2].str; }); while (!request.isDone) { } } catch (Exception e) { FbDebug.Log(e.StackTrace); } }
public static void verifyGameID(string gameID) { print("Setting game ID..." + gameID); string urlconcat = "http://sgicollab1.herokuapp.com/add_user_to_game" + "?game_id=" + gameID + "&auth_token=" + token; var r = new HTTP.Request("GET", urlconcat); r.Send(); while (!r.isDone) { if (r.exception != null) { Debug.Log(r.exception.ToString()); } } if (r.exception != null) { Debug.Log(r.exception.ToString()); } else { Debug.Log(r.response.Text); if (r.response.Text == "user not signed in") { PhotonNetwork.LeaveRoom(); } } }
public void LoadRanking(int levelID) { string url = SocialManager.Instance.FIREBASE + "/level" + levelID + ".json?orderBy=\"score\"&limitToLast=30"; Debug.Log("LoadRanking: " + url); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { Hashtable decoded = (Hashtable)JSON.JsonDecode(request.response.Text); if (decoded == null || decoded.Count == 0) { Debug.LogError("server returned null or malformed response ):"); return; } foreach (DictionaryEntry json in decoded) { Hashtable jsonObj = (Hashtable)json.Value; RankingData newData = new RankingData(); // s.id = (string)json.Key; newData.playerName = (string)jsonObj["playerName"]; newData.score = (int)jsonObj["score"]; newData.facebookID = (string)jsonObj["facebookID"]; levels[levelID - 1].data.Add(newData); } levels[levelID - 1].data = OrderByScore(levels[levelID - 1].data); }); }
IEnumerator Start() { var requests = new List<HTTP.Request> (); while (count > 0) { count --; var r = new HTTP.Request ("GET", url); r.Send (); requests.Add (r); } while (true) { var done = true; foreach (var r in requests) { done = done & r.isDone; if (r.exception != null) { Debug.Log (r.exception.ToString ()); } } yield return new WaitForSeconds (1); if (done) break; } foreach (var r in requests) { if (r.exception != null) { Debug.Log (r.exception.ToString ()); } else { Debug.Log(r.response.Text); } } Debug.Log("Finished."); }
IEnumerator _Send(Request request, System.Action<HTTP.Request> requestDelegate) { request.Send(); while(!request.isDone) yield return new WaitForEndOfFrame(); requestDelegate(request); }
void OnSaveBlockToDB(string title, string content) { print("OnSaveBlockToDB title: " + title + "result: " + content); Hashtable blockData = new Hashtable(); blockData.Add("title", title); blockData.Add("content", content); Hashtable data = new Hashtable(); data.Add( Data.Instance.userData.totalBlocksNotes.ToString() , blockData); string url = SocialManager.Instance.FIREBASE + "/users/" + Data.Instance.userData.userID + "/block/.json"; Debug.Log(url); HTTP.Request theRequest = new HTTP.Request("patch", url, data); theRequest.Send((request) => { Hashtable jsonObj = (Hashtable)JSON.JsonDecode(request.response.Text); if (jsonObj == null) { Debug.LogError("server returned null or malformed response ):"); } Debug.Log("block updated: " + request.response.Text); }); AchievementsEvents.OnNewBlockSended(); Events.OnBlockReset(); }
IEnumerator Start() { var w = new WWWForm(); w.AddField("hello", "world"); w.AddBinaryData("file", new byte[] { 65, 65, 65, 65 }); var r = new HTTP.Request(url, w); r.Send(); while (true) { if (r.exception != null) //some error occured. { Debug.Log(r.exception.ToString()); break; } if (r.state != HTTP.RequestState.Waiting) //there might be some chunks available { } yield return(new WaitForEndOfFrame()); } Debug.Log("Stream has finished"); }
public RestifizerResponse(HTTP.Request request, RestifizerError error, string tag) { this.Status = request.response.status; this.HasError = true; this.Error = error; this.Request = request; this.Tag = tag; }
public static IEnumerator delete(string url, string sessionToken, Action<bool,object> callback = null) { if (GamedoniaBackend.INSTANCE.debug) { String debugMsg = "[Api Call] - " + url; Debug.Log(debugMsg); } string path = _baseURL + "/" + _version + url; string date = GetCurrentDate(); Request request = new Request("delete",path); if (!string.IsNullOrEmpty(sessionToken)) request.AddHeader(GD_SESSION_TOKEN,sessionToken); request.AddHeader(GD_APIKEY, _apiKey); request.AddHeader("Date", date); request.AddHeader(GD_SIGNATURE, Sign(_apiKey, _secret, date, "DELETE", request.uri.AbsolutePath)); request.Send(); while (!request.isDone) { yield return null; } if (request.response.status == 200) { if (GamedoniaBackend.INSTANCE.debug) Debug.Log("[Api Response][" + url + "] - " + request.response.status + " " + request.response.Text); callback(true, request.response.Text); }else { printResponseLog(url, request.response); GDError error = GDError.buildError(request.response); GamedoniaBackend.INSTANCE.lastError = error; callback(false, request.response.message + ' ' + request.response.Text); } }
public IEnumerator check() { HTTP.Request checkDevice = new HTTP.Request("get", ServerInfo.serverURL + "/" + ServerInfo.API + "/" + ServerInfo.deviceApi + "/" + ServerInfo.device.getUniqueId()); checkDevice.Send(); while (!checkDevice.isDone) { yield return(new WaitForSeconds(0.1f)); } deviceObject = new JSONObject(checkDevice.response.Text); if (deviceObject[2].ToString().Contains("EVET")) { Debug.Log("Ozel ayarlar VAR"); DateTime baslangicSaati = DateTime.Parse(deviceObject[3].ToString().Trim('"')); DateTime bitisSaati = DateTime.Parse(deviceObject[4].ToString().Trim('"')); Debug.Log("****************************************************************"); Debug.Log("Başlangıc: " + baslangicSaati + " | Bitis: " + bitisSaati); Debug.Log("****************************************************************"); controller.saatleriAyarla(baslangicSaati, bitisSaati); } else { Debug.Log("Ozel ayarlar YOK"); getGeneralTimeSettings(); } }
public void registerDevice() { Hashtable data = new Hashtable(); data.Add("uniqueId", ServerInfo.device.getUniqueId()); data.Add("deviceName", ServerInfo.device.getDeviceName()); data.Add("override", "HAYIR"); data.Add("timeStart", ""); data.Add("timeEnd", ""); data.Add("notes", ""); HTTP.Request registerDevice = new HTTP.Request("post", ServerInfo.serverURL + "/" + ServerInfo.API + "/" + ServerInfo.deviceApi, data); registerDevice.Send((request) => { Hashtable result = request.response.Object; if (result == null) { Debug.LogWarning("Cannot register device"); registerFailed(); return; } registerSuccess(); }); }
public IEnumerator _Refresh(GameObject plane, Position center) { string url = "http://maps.googleapis.com/maps/api/staticmap?"; string qs = ""; qs += "center=" + HTTP.URL.Encode(string.Format("{0},{1}", center.latitute, center.lontitute)); qs += "&zoom=" + zoom.ToString(); qs += "&size=" + HTTP.URL.Encode(string.Format("{0}x{0}", size)); qs += "&scale=2"; qs += "&maptype=terrain&key=AIzaSyAWzOOJz0eZ8bs294s_PJdfOs8nz-s9xKc"; var req = new HTTP.Request("GET", url + qs, true); req.Send(); while (!req.isDone) { yield return(null); } if (req.exception == null) { var tex = new Texture2D(size, size); tex.LoadImage(req.response.Bytes); plane.GetComponent <Renderer>().material.mainTexture = tex; } }
/// <summary> /// Fetches the given path in the Graph API. /// /// Translates args to a valid query string. If post_args is given, /// sends a POST request to the given path with the given arguments. /// </summary> /// <param name="path">The path where the request is to be send</param> /// <param name="args">The Query arguments</param> /// <param name="postArgs">The POST arguments</param> /// <returns>A JObject of the facebook response</returns> private HTTP.Request SendRequest(string path, Dictionary <string, string> args, Dictionary <string, string> postArgs) { if (!isLogined) { throw new FacebookGraphAPIException("not logined", "Login to perform action"); } if (args == null) { args = new Dictionary <string, string> (); } if (postArgs != null) { postArgs["access_token"] = accessToken; } else { args["access_token"] = this.accessToken; } string uri = "https://graph.facebook.com/" + path + "?" + EncodeDictionary(args); var request = new HTTP.Request("POST", uri); if (postArgs != null) { request.Text = EncodeDictionary(postArgs); } return(request); }
public void RegisterPoints(Vector3[] points) { int counter = 0; string flow = "["; for(int i = 0; i < points.Length; i++) { if(counter != 0) flow += ","; flow += points[i].x + "," + points[i].y + "," + points[i].z; counter++; if(counter >= MAX_POINTS_PER_REQUEST) { flow += "]"; byte[] input = Encoding.UTF8.GetBytes(flow); HTTP.Request someRequest = new HTTP.Request( "post", url + "/points", input ); someRequest.AddHeader("Content-Type", "application/json"); someRequest.Send( ( request ) => { // LOGGER Debug.Log( request.response.Text ); }); flow = "["; counter = 0; } } // TODO regiser last batch of points flow += "]"; }
private void PostToDB(string userName, string encryptPw) { Hashtable data = new Hashtable(); data.Add("UserName", userName); data.Add("password", encryptPw); data.Add("name", "kok"); data.Add("score", 0); // When you pass a Hashtable as the third argument, we assume you want it send as JSON-encoded // data. We'll encode it to JSON for you and set the Content-Type header to application/json HTTP.Request theRequest = new HTTP.Request("post", url, data); theRequest.Send((request) => { // we provide Object and Array convenience methods that attempt to parse the response as JSON // if the response cannot be parsed, we will return null // note that if you want to send json that isn't either an object ({...}) or an array ([...]) // that you should use JSON.JsonDecode directly on the response.Text, Object and Array are // only provided for convenience Hashtable result = request.response.Object; if (result == null) { Debug.LogWarning("Could not parse JSON response!"); return; } else { Debug.Log("pass naja"); } }); }
//void LoadChallenge(bool _received, ParseQuery<ParseObject> query) //{ // query.FindAsync().ContinueWith(t => // { // IEnumerable<ParseObject> results = t.Result; // // if (_received && loaded_received) return; // if (!_received) // { // if( made_state == state.READY) return; // made.Clear(); // } // foreach (var result in results) // { // string objectID = result.ObjectId; // string facebookID = result.Get<string>("facebookID"); // string op_facebookID = result.Get<string>("op_facebookID"); // string op_playerName = result.Get<string>("op_playerName"); // string playerName = result.Get<string>("playerName"); // bool notificated = result.Get<bool>("notificated"); // int level = result.Get<int>("level"); // float score = result.Get<float>("score"); // float score2 = 0; // string winner = ""; // try // { // score2 = result.Get<float>("score2"); // winner = result.Get<string>("winner"); // } // catch // { // } // PlayerData playerData = new PlayerData(); // playerData.objectID = objectID; // playerData.facebookID = facebookID; // playerData.playerName = playerName; // playerData.notificated = notificated; // if (!_received) // { // playerData.facebookID = op_facebookID; // playerData.playerName = op_playerName; // } // playerData.score = score; // playerData.level = level; // playerData.winner = winner; // playerData.score2 = score2; // if (_received) // { // received.Add(playerData); // // loaded_received = true; // } // else // { // made.Add(playerData); // made_state = state.READY; // } // } // } // ); //} void OnChallengeCreate(string oponent_username, string oponent_facebookID, int score) { made_state = state.REFRESHING; Hashtable data = new Hashtable(); data.Add("facebookID", SocialManager.Instance.userData.facebookID); data.Add("playerName", SocialManager.Instance.userData.username); data.Add("op_playerName", oponent_username); data.Add("op_facebookID", oponent_facebookID); data.Add("score", score); data.Add("score2", 0); data.Add("notificated", false); Hashtable time = new Hashtable(); time.Add(".sv", "timestamp"); data.Add("time", time); HTTP.Request theRequest = new HTTP.Request("post", SocialManager.Instance.FIREBASE + "/challenges.json", data); theRequest.Send((request) => { Hashtable jsonObj = (Hashtable)JSON.JsonDecode(request.response.Text); if (jsonObj == null) { Debug.LogError("server returned null or malformed response ):"); } Debug.Log("__OnChallengeCreated!"); LoadMade(); }); }
public void LoadRanking() { data = new List<RankingData>(); string url = SocialManager.Instance.FIREBASE + "/" + TABLE + ".json?orderBy=\"achievements\"&limitToLast=100"; Debug.Log("LoadRanking: " + url); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { Hashtable decoded = (Hashtable)JSON.JsonDecode(request.response.Text); if (decoded == null || decoded.Count == 0) { Debug.LogError("server returned null or malformed response ):"); return; } foreach (DictionaryEntry json in decoded) { Hashtable jsonObj = (Hashtable)json.Value; RankingData newData = new RankingData(); // s.id = (string)json.Key; newData.username = (string)jsonObj["username"]; int ach = (int)jsonObj["achievements"]; print(ach); newData.achievements = ach; data.Add(newData); } data = OrderByScore(data); }); }
public IEnumerator uploadFile(string fileLocation) { FileStream fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read); byte[] filebytes = new byte[fs.Length]; fs.Read(filebytes, 0, Convert.ToInt32(fs.Length)); string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks); string urlenc = WWW.EscapeURL(encodedData); WWWForm parameters = new WWWForm(); parameters.AddField("plugin", MaterialiseKeys.PRODUCT_TYPE_ID); parameters.AddBinaryData("file", filebytes, "cube.stl", "application/x-octetstream"); string data = MiniJSON.Json.Serialize(parameters); HTTP.Request uploadRequest = new HTTP.Request(MaterialiseUrls.UPLOAD_URL, parameters); uploadRequest.OnRedirect = onRedirectCallback; uploadRequest.Send(); while (!uploadRequest.isDone) { yield return(new WaitForEndOfFrame()); } if (uploadRequest.exception != null) { Debug.Log(uploadRequest.exception); } else { modelUrl = uploadRequest.response.GetHeader("Location"); } }
void AddNewUserTODB(string username, string email, string password) { Debug.Log("AddNewUser" + username + "_" + email + "_" + password); Hashtable data = new Hashtable(); data.Add("username", username); data.Add("email", email); data.Add("password", password); data.Add("achievements", ""); Hashtable blockContent = new Hashtable(); blockContent.Add("title", ""); blockContent.Add("content", ""); data.Add("block", blockContent); HTTP.Request theRequest = new HTTP.Request("post", SocialManager.Instance.FIREBASE + "/users.json", data); theRequest.Send((request) => { Hashtable jsonObj = (Hashtable)JSON.JsonDecode(request.response.Text); if (jsonObj == null) { Debug.LogError("server returned null or malformed response ):"); } else { Debug.Log("nuevo usuario!!"); GetObjectID(email); } }); }
public IEnumerator getMaterials() { Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("user", MaterialiseKeys.EMAIL); HTTP.Request materialsRequest = new HTTP.Request("GET", MaterialiseUrls.MATERIALS_URL + toQueryString(parameters)); materialsRequest.SetHeader("Accept", "application/json"); materialsRequest.SetHeader("Content-type", "application/x-www-form-urlencoded"); materialsRequest.Send(); while (!materialsRequest.isDone) { yield return(new WaitForEndOfFrame()); } if (materialsRequest.exception != null) { Debug.LogError(materialsRequest.exception.ToString()); } else { IDictionary response = (IDictionary)MiniJSON.Json.Deserialize(materialsRequest.response.Text); this.materials = (IList)response["materials"]; } }
public void CreateUserIfNotExists(string username, string _email, string password) { Debug.Log("CreateUserIfNotExists: " + _email); string url = SocialManager.Instance.FIREBASE + "/users.json?orderBy=\"email\"&equalTo=\"" + _email + "\""; Debug.Log(url); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { Hashtable decoded = (Hashtable)JSON.JsonDecode(request.response.Text); if (decoded == null || decoded.Count == 0) { AddNewUserTODB(username, _email, password); return; } else if (decoded.Count > 0) { foreach (DictionaryEntry json in decoded) { Hashtable jsonObj = (Hashtable)json.Value; string id = (string)json.Key.ToString(); Data.Instance.userData.SaveObjectID(id); } Debug.Log("Ya existias"); } }); }
IEnumerator Download(Request request, DiskCacheOperation handle) { request.Send (); while (!request.isDone) yield return new WaitForEndOfFrame (); handle.isDone = true; }
void Start() { urlconcat = "?user[name]=eric&user[email][email protected]&user[password]=password&user[password_confirmation]=password"; var requests = new List<HTTP.Request> (); while (count > 0) { count --; var r = new HTTP.Request ("POST", url+urlconcat); r.Send (); requests.Add (r); } while (true) { var done = true; foreach (var r in requests) { done = done & r.isDone; if (r.exception != null) { Debug.Log (r.exception.ToString ()); } } if (done) break; } foreach (var r in requests) { if (r.exception != null) { Debug.Log (r.exception.ToString ()); } else { Debug.Log(r.response.Text); } } Debug.Log("Finished."); }
public DiskCacheOperation Fetch (Request request) { var handle = new DiskCacheOperation (); handle.request = request; StartCoroutine (Download (request, handle)); return handle; }
// Query Access Token Coroutine IEnumerator QueryAccessToken(string name, string password) { // Populate HTML request HTTP.Request request = new HTTP.Request("POST", "http://api.stackmob.com/user/accessToken"); request.Text = string.Format("username={0}&password={1}&token_type=mac", name, password); // Add request headers request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddHeader("Accept", acceptHeader); request.AddHeader("X-StackMob-API-Key", apiKey); request.AddHeader("X-StackMob-User-Agent", "StackMob Platform"); // Send request request.Send(); // Yield coroutine until request returns while (!request.isDone) { yield return(null); } // Dump request response to debug console Debug.Log(request.response.Text); // Parse JSON object Hashtable table = JSON.JsonDecode(request.response.Text) as Hashtable; // Store Mac Key & Access Token accessToken = GetString("access_token", table); macKey = GetString("mac_key", table); // Query a schema with permissions enabled (ie. Allow any logged in user) StartCoroutine(Query("GET", "http://api.mob1.stackmob.com/safe")); }
void LoadHiscoreFromDB(int LevelID) { string url = SocialManager.Instance.FIREBASE + "/level" + LevelID + ".json?orderBy=\"facebookID\"&equalTo=\"" + SocialManager.Instance.userData.facebookID + "\""; Debug.Log(url); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { Hashtable decoded = (Hashtable)JSON.JsonDecode(request.response.Text); isLoaded = true; if (decoded == null) { Debug.Log("no existe el user or malformed response ):"); return; } else if (decoded.Count == 0) { SetHiscore(LevelID, 0); } else { foreach (DictionaryEntry json in decoded) { Hashtable jsonObj = (Hashtable)json.Value; //Score s = new Score(); string id = (string)json.Key.ToString(); SetDB_ID(LevelID, id); int hiscore = (int)jsonObj["score"]; SetHiscore(LevelID, hiscore); } } }); }
public static void verifyGameID(string gameID) { print("Setting game ID..." + gameID); string urlconcat ="http://sgicollab1.herokuapp.com/add_user_to_game" + "?game_id=" + gameID + "&auth_token=" + token; var r = new HTTP.Request ("GET", urlconcat); r.Send (); while (!r.isDone) { if (r.exception != null) { Debug.Log (r.exception.ToString ()); } } if (r.exception != null) { Debug.Log (r.exception.ToString ()); } else { Debug.Log(r.response.Text); if(r.response.Text == "user not signed in"){ PhotonNetwork.LeaveRoom(); } } }
// public static void setData(string username, string password, string data){ // // string urlconcat = "?user[name]=" + username + // "&user[password]=" + password + // "&auth_token=" + token + // "&user["+ data +"]=" + data; // // var r = new HTTP.Request ("PUT", url + urlconcat); // r.Send (); // while (!r.isDone) { // if (r.exception != null) { // Debug.Log (r.exception.ToString ()); // } // } // // if (r.exception != null) { // Debug.Log (r.exception.ToString ()); // } else { // Debug.Log(r.response.Text); // // } // } public static IEnumerator verifyUser() { print("Verifying..."); string urlconcat ="/signedin" + "?auth_token=" + token; var r = new HTTP.Request ("POST", url + urlconcat); r.Send (); while (!r.isDone) { if (r.exception != null) { Debug.Log (r.exception.ToString ()); } } if (r.exception != null) { Debug.Log (r.exception.ToString ()); } else { Debug.Log(r.response.Text); if(r.response.Text == "not signed in") { //destroy the code object here! Otherwise when we go back to main we'll actually *duplicate* it, which is what we don't want because //it messes up the main menu. PhotonNetwork.LeaveRoom(); Destroy(GameObject.Find("Code")); Application.LoadLevel(0); } } yield return null; }
//User log in public static IEnumerator login(string username, string password) { print("Logging in..."); string urlconcat ="/sign_in" + "?user[name]=" + username + "&user[password]=" + password; var r = new HTTP.Request ("POST", url + urlconcat); r.Send (); while (!r.isDone) { if (r.exception != null) { Debug.Log (r.exception.ToString ()); } } if (r.exception != null) { Debug.Log (r.exception.ToString ()); } else { Debug.Log(r.response.Text); Hashtable json = (Hashtable)JsonSerializer.Decode(r.response.Bytes); if (json.ContainsKey ("auth_token")) { token = json["auth_token"].ToString(); MainMenuVik.maxLevelData = (int)json["maxStageReached"]; MainMenuVik.userTally = true; loggedIn = true; }else{ MainMenuVik.userTally = false; } } yield return null; }
IEnumerator TimeoutExample() { float initialTime = Time.realtimeSinceStartup; var r = new HTTP.Request("GET", "http://krogh.no/wp-content/uploads/2011/09/earth-huge.png"); r.acceptGzip = false; r.useCache = false; r.timeout = 1; yield return(r.Send()); Debug.Log("Time: " + (Time.realtimeSinceStartup - initialTime) + "s"); if (r.exception != null) { if (r.exception is System.TimeoutException) { Debug.Log("Request timed out."); } else { Debug.Log("Exception occured in request."); } } else { Debug.Log("Result received within timeout."); } }
IEnumerator Start() { var uniwebSeconds = 0.0; var wwwSeconds = 0.0; //Warm up engines. yield return(new HTTP.Request("GET", "http://www.differentmethods.com/").Send()); yield return(new WWW("http://www.differentmethods.com/")); for (var i = 0; i < 10; i++) { var clock = new Stopwatch(); var req = new HTTP.Request("GET", "http://www.differentmethods.com/"); clock.Start(); yield return(req.Send()); clock.Stop(); uniwebSeconds += clock.Elapsed.TotalSeconds; } for (var i = 0; i < 10; i++) { var clock = new Stopwatch(); var req = new WWW("http://www.differentmethods.com/"); clock.Start(); yield return(req); clock.Stop(); wwwSeconds += clock.Elapsed.TotalSeconds; } UnityEngine.Debug.Log("UniWeb: " + (uniwebSeconds / 10)); UnityEngine.Debug.Log("WWW: " + (wwwSeconds / 10)); }
public static string getGameID() { print("Getting game ID..."); string level = GameManagerVik.nextLevel.ToString(); Debug.Log("level = " + level); string urlconcat ="http://sgicollab.herokuapp.com/game" + "?auth_token=" + token + "&game[level]=" + level; var r = new HTTP.Request ("POST", urlconcat); r.Send (); while (!r.isDone) { if (r.exception != null) { Debug.Log (r.exception.ToString ()); } } if (r.exception != null) { Debug.Log (r.exception.ToString ()); } else { Debug.Log(r.response.Text); return r.response.Text; } return null; }
protected void AddNewHiscore(int levelID, int score) { Hashtable data = new Hashtable(); data.Add("facebookID", SocialManager.Instance.userData.facebookID); data.Add("playerName", SocialManager.Instance.userData.username); data.Add("score", score); Hashtable time = new Hashtable(); time.Add(".sv", "timestamp"); data.Add("time", time); HTTP.Request theRequest = new HTTP.Request("post", SocialManager.Instance.FIREBASE + "/level" + levelID + ".json", data); theRequest.Send((request) => { Hashtable jsonObj = (Hashtable)JSON.JsonDecode(request.response.Text); if (jsonObj == null) { Debug.LogError("server returned null or malformed response ):"); } Debug.Log("GRABO NUVEO SCORE"); SetHiscore(levelID, score); //vuelve a levantarlo para grabar el id: LoadHiscoreFromDB(levelID); }); }
public void LoadReceived() { received_state = state.LOADING; received.Clear(); string url = SocialManager.Instance.FIREBASE + "/challenges.json"; //?orderBy=\"time\"&limitToLast=30"; url += "?orderBy=\"op_facebookID\"&equalTo=\"" + SocialManager.Instance.userData.facebookID + "\""; Debug.Log("LoadReceived: " + url); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { Hashtable decoded = (Hashtable)JSON.JsonDecode(request.response.Text); if (decoded == null) { Debug.LogError("server returned null or malformed response ):"); return; } foreach (DictionaryEntry json in decoded) { Hashtable jsonObj = (Hashtable)json.Value; PlayerData newData = new PlayerData(); newData.objectID = (string)json.Key; newData.facebookID = (string)jsonObj["facebookID"]; newData.playerName = (string)jsonObj["playerName"]; newData.score = (int)jsonObj["score"]; newData.score2 = (int)jsonObj["score2"]; newData.winner = (string)jsonObj["winner"]; newData.notificated = (bool)jsonObj["notificated"]; received.Add(newData); } received_state = state.READY; }); }
void requestGyroscope() { HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send((request) => { requestGyroscope(); transform.eulerAngles = gyroscopeSerializer.getAxis(request.response.Text); }); }
public override void GET(HTTP.Request request) { var response = request.response; response.status = 200; response.message = "OK"; response.Text = "Hello, World!"; }
public RestifizerResponse(HTTP.Request request, ArrayList result, string tag) { this.IsList = true; this.Status = request.response.status; this.ResourceList = result; this.HasError = false; this.Request = request; this.Tag = tag; }
public void Snapshot() { var request = new HTTP.Request("GET", URL("/snapshot.cgi")); request.Send((obj) => { texture.LoadImage(obj.Bytes); }); }
private static void HTTP_Get(string url, Action <HTTP.Response> onResponseAction) { var request = new HTTP.Request("get", url); request.Send((r) => { onResponseAction(r.response); }); }
private static void HTTP_Post(string url, WWWForm body, Action <HTTP.Response> onResponseAction) { var request = new HTTP.Request("post", url, body); request.Send((r) => { onResponseAction(r.response); }); }
IEnumerator StartDownload() { var urls = new string[] { "http://www.differentmethods.com/wp-content/uploads/2011/05/uniweb.jpg", "http://www.differentmethods.com/wp-content/uploads/2011/05/react.jpg", "http://entitycrisis.blogspot.com/" }; //Only needed in WebPlayer //Security.PrefetchSocketPolicy("www.differentmethods.com", 843); for (var i = 0; i < 5; i++) { var requests = new List <HTTP.Request> (); foreach (var url in urls) { var r = new HTTP.Request("GET", url); r.Send(); requests.Add(r); Debug.Log(r); } while (true) { yield return(null); var done = true; foreach (var r in requests) { done = done & r.isDone; } if (done) { break; } } foreach (var r in requests) { if (r.exception != null) { Debug.LogError(r.exception); } else { var tex = new Texture2D(512, 512); tex.LoadImage(r.response.Bytes); renderer.material.SetTexture("_MainTex", tex); yield return(new WaitForSeconds(1)); } } yield return(new WaitForSeconds(30)); } }
void Start() { guiText.fontSize = Mathf.RoundToInt(Camera.main.pixelHeight / 14f); HTTP.Request someRequest = new HTTP.Request("get", "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=44db6a862fba0b067b1930da0d769e98"); someRequest.Send( ( request ) => { // parse some JSON, for example: JSONObject thing = new JSONObject( request.response.Text ); Debug.Log(thing); }); }
IEnumerator TestHTTP10() { var r = new HTTP.Request("GET", "http://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination?lat1=-36.8518&lon1=174.8554&resultFormat=xml"); yield return r.Send(); if(r.exception == null) { Debug.Log(r.response.status); Debug.Log(r.response.Text); } else { Debug.LogError(r.exception); } }
void Start() { guiText.fontSize = Mathf.RoundToInt(Camera.main.pixelHeight / 14f); HTTP.Request someRequest = new HTTP.Request("get", "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=44db6a862fba0b067b1930da0d769e98"); someRequest.Send((request) => { // parse some JSON, for example: JSONObject thing = new JSONObject(request.response.Text); Debug.Log(thing); }); }
public override void GET(HTTP.Request request) { var response = request.response; var x = new Hashtable(); x["boo"] = "ya!"; response.Text = HTTP.JsonSerializer.Encode(x); response.headers.Set("Content-Type", "application/json"); }