private IEnumerator queryCoordinatesSQL(string url) { //stopwatch.Start(); // 开始监视代码运行时间 List <IMultipartFormSection> formData = new List <IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("itemName", gameObject.name)); url += "?action=querycoordinates"; UnityWebRequest www = UnityWebRequest.Post(url, formData); www.chunkedTransfer = false; yield return(www.SendWebRequest()); if (www.error != "" && www.error != null) { Debug.Log(www.error); } else { Debug.Log("Form queryall complete!" + www.downloadHandler.text); string xml = www.downloadHandler.text; if (xml.Length > 10) { string[] buildinginfos = xml.Split('\n'); List <string> buildinglist = new List <string>(); int i = 0; foreach (string building in buildinginfos) { if (building.Length > 10) { string[] buildinginfo = building.Split('\t'); string itemName = buildinginfo[0]; buildinglist.Add(itemName); float obj_longtitude = float.Parse(buildinginfo[1]); float obj_latitude = float.Parse(buildinginfo[2]); Quaternion obj_rotation = Quaternion.Euler(float.Parse(buildinginfo[3]), float.Parse(buildinginfo[4]), float.Parse(buildinginfo[5])); Vector3 obj_scale = new Vector3(float.Parse(buildinginfo[6]), float.Parse(buildinginfo[7]), float.Parse(buildinginfo[8])); var tileUL = terrainmap._place.Location.ToTile(terrainmap._place.Level); var tileLR = new Tile() { Zoom = tileUL.Zoom, X = tileUL.X + terrainmap.CHILDREN_LEVEL * 2, Y = tileUL.Y + terrainmap.CHILDREN_LEVEL * 2 }; var coordUL = tileUL.UpperLeft(terrainmap.CHILDREN_LEVEL); var coordLR = tileLR.UpperLeft(terrainmap.CHILDREN_LEVEL); // Get tapped location relative to lower left. GameObject terrain = GameObject.Find("terrain"); Vector3 locationonMap = new Vector3(); locationonMap.x = (obj_longtitude - coordUL.Longitude) / (coordLR.Longitude - coordUL.Longitude) * terrainmap.SIZE; locationonMap.z = (1 - (obj_latitude - coordUL.Latitude) / (coordLR.Latitude - coordUL.Latitude)) * terrainmap.SIZE; locationonMap.y = 0.02f; var positiononMap = locationonMap + terrain.transform.position; if ((positiononMap.x <= terrain.transform.position.x + terrainmap.SIZE) && (positiononMap.x >= terrain.transform.position.x) && (positiononMap.z <= terrain.transform.position.z + terrainmap.SIZE) && (positiononMap.z >= terrain.transform.position.z)) { if (GameObject.Find(itemName) == null) { string assetbundleURL = "http://" + networkAddress + ":" + networkPort + "/assetbundle/" + "BasicModule" + ".assetbundle"; StartCoroutine(GetAssetBundle(assetbundleURL, positiononMap, obj_rotation, obj_scale, itemName)); } } else { if (GameObject.Find(itemName) != null) { Destroy(GameObject.Find(itemName).gameObject); } } } } GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("Rotate"); for (var j = 0; j < gameObjects.Length; j++) { if (!buildinglist.Contains(gameObjects[j].name)) { Destroy(gameObjects[i]); } } } } }
IEnumerator PostTransaction(string uuid) { //Form WWWForm form = new WWWForm(); form.AddField("uuid", uuid); UnityWebRequest www = UnityWebRequest.Post("http://pkm-tol.herokuapp.com/public/api/transaction/12", form); www.SendWebRequest(); //Waiting Upload while (www.isDone == false) { Debug.Log("Menuggu Upload"); yield return(www); Debug.Log(www.ToString()); } //Belum Selesai Download if (www.downloadHandler.isDone == false) { Debug.Log("Menunggu Download"); yield return(www); Debug.Log(www.downloadHandler.text); } if (www.error == null) { if (www.downloadHandler.isDone) { //Query Selesai Debug.Log("Selesai"); //Debug.Log(www.downloadHandler.text); string json = www.downloadHandler.text; Transaction myTrans = new Transaction(); myTrans = JsonUtility.FromJson <Transaction>(json); Session.GetInstance().Price = myTrans.price; Session.GetInstance().Masuk = myTrans.masuk; Session.GetInstance().Keluar = myTrans.keluar; PlayerPrefs.SetString("Price", myTrans.price); PlayerPrefs.SetString("Masuk", myTrans.masuk); PlayerPrefs.SetString("Keluar", myTrans.keluar); string a = "Masuk : " + Session.GetInstance().Masuk; string b = "Keluar : " + Session.GetInstance().Keluar; string c = "Harga : " + Session.GetInstance().Price; text[0].text = a; text[1].text = b; text[2].text = c; PopUpTransaksion.active = true; } } else { Debug.Log(www.error); } }
public static void POST(string details, string token, bool async, System.Action <string> handler) { details = details.Trim('\r'); details = QuerySorter(details); string jsonData = ""; Query query = new Query { query = details }; jsonData = JsonUtility.ToJson(query); if (Enjin.SDK.Core.Enjin.IsDebugLogActive) { if (!jsonData.Contains("password:"******"accessTokens:")) { Debug.Log("<color=orange>[GRAPHQL QUERY]</color> " + jsonData); } } UnityWebRequest request = UnityWebRequest.Post(Enjin.SDK.Core.Enjin.GraphQLURL, UnityWebRequest.kHttpVerbPOST); request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(jsonData)) as UploadHandler; request.SetRequestHeader("Content-Type", "application/json; charset=utf-8"); if (token != "login") { request.SetRequestHeader("Authorization", "Bearer " + Enjin.SDK.Core.Enjin.AccessToken); } request.downloadHandler = new DownloadHandlerBuffer(); if (request.error != null) { Enjin.SDK.Core.Enjin.IsRequestValid(request.responseCode, request.downloadHandler.text); } else { if (async) { instance.StartCoroutine(WaitForRequest(request, handler)); queryStatus = Status.Loading; } else if (!async) { request.SendWebRequest(); while (!request.isDone) { } if (Enjin.SDK.Core.Enjin.IsRequestValid(request.responseCode, request.downloadHandler.text)) { queryStatus = Status.Complete; queryReturn = request.downloadHandler.text; } } } // NOTE: Turn this conversion on once methods are updated to support this structure //queryReturn = Regex.Replace(queryReturn, @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+", "$1"); if (Enjin.SDK.Core.Enjin.IsDebugLogActive && queryReturn != null) { Debug.Log("<color=orange>[GRAPHQL RESULTS]</color> " + queryReturn.ToString()); } }
//앱이 실행될 때 동작하는 함수 public void Awake() { //플레이어프렙스에 id key가 있는지 확인 if (PlayerPrefs.HasKey("id") == true) { Debug.Log("1 , PlayerPrefs.HasKey(id) ok"); //이 시점에 upload 함수를 실행 StartCoroutine(Upload()); Debug.Log("5.5 , coroutine 종료 되고 ienumerator 나머지 동작"); } else { //플레이어프렙스에 id key가 없음 로그인 한 기록이 없거나 로그아웃 했음 Debug.Log("1 , PlayerPrefs.HasKey(id) no"); } IEnumerator Upload() { //form 과 그 안에 들어가는 변수 //저장된 아이디 string id = PlayerPrefs.GetString("id"); Debug.Log("2 id:" + id); //저장된 패스워드 string pw = PlayerPrefs.GetString("pw"); Debug.Log("3 pw:" + pw); //저장된 로그인 방식 string logincategory = PlayerPrefs.GetString("logincategory"); Debug.Log("4 logincategory:" + logincategory); //이전에 로그인한 방식이 robotwar계정 로그인 이라면 if (logincategory == "robotwar") { //w에 id,pw를 합쳐서 post로 전달 WWWForm w = new WWWForm(); w.AddField("select", "submit"); w.AddField("id", id); w.AddField("pw", pw); UnityWebRequest www = UnityWebRequest.Post("http://49.247.131.90/login.php", w); Debug.Log("5 , http://49.247.131.90/login.php에 post"); yield return(www.SendWebRequest()); //서버 연결 실패 if (www.isNetworkError || www.isHttpError) { Debug.Log("6 , 네트워크 연결 실패 errcode: " + www.error); } else //서버 연결 성공 { //php에서 echo로 전달 되는 데이터를 변수로 만듦 string result = www.downloadHandler.text; Debug.Log("6 , 네트워크 연결 성공 result: " + result); if (result == "ok") { Debug.Log("7 , goto main"); //메인 신으로 넘어가는 함수 SceneManager.LoadScene("mainscene"); } else { Debug.Log("7 , result not ok / dont go"); } } } //이전 로그인이 facebook로그인으로 이루어져 있을 때 else if (logincategory == "facebook") { Debug.Log("5 , facebook login 함수 실행"); //facebook 스크립트가 들어있는 오브젝트에서 스크립트를 참고하는 함수 var facebook = GameObject.Find("facebook").GetComponent <facebookback>(); //facebook 스크립트의 로그인 함수 facebook.Initcheck(); } } }
public IEnumerator RequestSync(string url, HTTPMethods methods = HTTPMethods.Get, Dictionary <string, string> headers = null, WWWForm param = null, Action <DownloadHandler> onSuccess = null, Action <float> onProgress = null, Action <DownloadHandler> onError = null) { switch (methods) { case HTTPMethods.Get: StringBuilder getUrl = new StringBuilder(url); if (param != null) { getUrl.Append("?"); getUrl.Append(Encoding.UTF8.GetString(param.data)); } webRequest = UnityWebRequest.Get(getUrl.ToString()); break; case HTTPMethods.Post: webRequest = UnityWebRequest.Post(url, param); break; case HTTPMethods.Put: byte[] bodyData = null; if (param != null) { bodyData = param.data; } webRequest = UnityWebRequest.Put(url, bodyData); break; case HTTPMethods.Delete: StringBuilder deleteUrl = new StringBuilder(url); if (param != null) { deleteUrl.Append("?"); deleteUrl.Append(Encoding.UTF8.GetString(param.data)); } webRequest = UnityWebRequest.Delete(deleteUrl.ToString()); break; case HTTPMethods.Head: StringBuilder headUrl = new StringBuilder(url); if (param != null) { headUrl.Append("?"); headUrl.Append(Encoding.UTF8.GetString(param.data)); } webRequest = UnityWebRequest.Head(headUrl.ToString()); break; } if (headers != null) { foreach (KeyValuePair <string, string> header in headers) { webRequest.SetRequestHeader(header.Key, header.Value); } } if (customDownloadHandler != null) { webRequest.downloadHandler = customDownloadHandler; } // 通信の前後でRequestとResponseのLogをとり、通信にかかった時間を計測する Stopwatch stopWatch = new Stopwatch(); HTTPLogger.LogRequest(webRequest, param, headers); stopWatch.Start(); webRequest.SendWebRequest(); while (!webRequest.isDone) { if (onProgress != null) { onProgress(webRequest.downloadProgress); } yield return(null); } if (onProgress != null) { onProgress(1.0f); } stopWatch.Stop(); HTTPLogger.LogResponse(webRequest, stopWatch.Elapsed, param); if (webRequest.isHttpError) { if (onError != null) { onError(webRequest.downloadHandler); } } else { if (onSuccess != null) { onSuccess(webRequest.downloadHandler); } } yield return(webRequest.downloadHandler); customDownloadHandler = null; }
IEnumerator LikeLevelProcess(int id, string currentUsername, LevelInfo level) { string url = serverURL + "CheckUserLike.php"; WWWForm w = new WWWForm(); w.AddField("id", id); using (UnityWebRequest www = UnityWebRequest.Post(url, w)) { yield return(www.SendWebRequest()); if (www.error != null) { Debug.Log("404 not found"); yield break; } else if (www.downloadHandler.text.Contains("Error")) { Debug.Log(www.downloadHandler.text); yield break; } else { string user = ""; string usersLiked = www.downloadHandler.text; for (int i = 0; i < usersLiked.Length; ++i) { if (usersLiked[i] == ',') { if (user == currentUsername) { int l = user.Length + 1; int j = i - user.Length; List <char> users = new List <char>(usersLiked); while (l > 0) { users.Remove(users[j]); --l; } //Dislike StartCoroutine(AddLike(id, -1, new string(users.ToArray()), level)); yield break; } user = ""; continue; } user += usersLiked[i]; } usersLiked += currentUsername + ","; // Like StartCoroutine(AddLike(id, 1, usersLiked, level)); } } }
//public void TestWordCloudRestClient() { //} /// <summary> /// In this method, we actually invoke a request to the outside server /// </summary> public override IEnumerator AsyncRequest(string jsonPayload, string method, string url, string success, string error) { if (!url.StartsWith("http")) { url = "http://" + url; } UnityWebRequest webRequest; Debug.Log("Payload is: " + jsonPayload); if (jsonPayload != "0") { var form = new WWWForm(); form.AddField("message", jsonPayload); // IMPORTANT: Assumes there is a form with THIS PARICULAR NAME OF FIELD webRequest = UnityWebRequest.Post(url, form); } else { // Only really handles the initialization step, to see if the server is, in fact, real webRequest = new UnityWebRequest(url + route, method); // route is specific page as directed by server var payloadBytes = string.IsNullOrEmpty(jsonPayload) ? Encoding.UTF8.GetBytes("{}") : Encoding.UTF8.GetBytes(jsonPayload); UploadHandler upload = new UploadHandlerRaw(payloadBytes); webRequest.uploadHandler = upload; webRequest.downloadHandler = new DownloadHandlerBuffer(); webRequest.SetRequestHeader("Content-Type", "application/json"); } webRequest.SendWebRequest(); int count = 0; // Try several times before failing while (count < 20) // 2 seconds max is good? Probably. { yield return(new WaitForSeconds((float)0.1)); // Totally sufficient if (webRequest.isNetworkError || webRequest.isHttpError) { Debug.LogWarning("Some sort of network error: " + webRequest.error + " from " + url); } else { // Show results as text if (webRequest.downloadHandler.text != "") { last_read = webRequest.downloadHandler.text; //BroadcastMessage("LookForNewParse"); // Tell something, in JointGestureDemo for instance, to grab the result if (webRequest.downloadHandler.text != "connected") { // Really needs to change. SingleAgentInteraction isn't gonna be extensible in our package-based future // And I didn't ever put together that LookForNewParse function either, this section is just a ghost :P SingleAgentInteraction sai = GameObject.FindObjectOfType <SingleAgentInteraction>(); sai.SendMessage("LookForNewParse"); } else { // Blatantly janky WordCloudIOClient parent = GameObject.FindObjectOfType <WordCloudIOClient>(); parent.wordcloudrestclient = this; // Ew, disgusting } Debug.Log("Server took " + count * 0.1 + " seconds"); POST_okay(count * 0.1); // Parameter literally means nothing here. break; } } count++; } if (count >= 20) { Debug.LogWarning("WordCloud Server took 2+ seconds "); Debug.LogWarning(webRequest.uploadHandler.data); } }
private IEnumerator LoadLevelGameData() { string address = Application.absoluteURL == string.Empty ? StaticDb.serverAddressEditor : Application.absoluteURL.TrimEnd('/'); //GET THE CORRECT LEVELMANAGER manager = SetLevelManager(); //CREATE NEW WWWFORM FOR GETTING DATA WWWForm form = new WWWForm(); //Debug.Log("manager.GetGameData().indexSlot: " + manager.GetGameData().indexSlot); //ADD FIELD TO FORM form.AddField("mode", "r"); form.AddField("mainDataFolder", StaticDb.mainDataFolder); form.AddField("playerFolder", StaticDb.player.folderName); form.AddField("saveFolder", StaticDb.saveFolder); //form.AddField("saveFileName", StaticDb.slotName + manager.GetGameData().indexSlot + StaticDb.slotExt); form.AddField("saveFileName", StaticDb.gameSaveName + StaticDb.gameSaveExt); //DOWNLOAD JSON DATA FOR GAMEDATA CLASS using (UnityWebRequest www = UnityWebRequest.Post( Path.Combine(address, Path.Combine(StaticDb.phpFolder, StaticDb.playerSaveManagerScript)), form)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { //Debug.Log(www.downloadHandler.text); if (www.downloadHandler.text == "Error Reading File") { //file neither exits or couldn't open it } else { //Get values to create game settings string data = www.downloadHandler.text; //SET GAMEDATA VARIABLE WITH JSON DATA DESERIALIZED gameData = JsonUtility.FromJson <GameData>(data); //SET DATE VALUE gameData.date = DateTime.FromFileTimeUtc(gameData.longDate); //SET MANAGER GAMEDATA WITH GAMEDATA VALUES RETRIEVED FROM SERVER manager.SetGameData(gameData); } } } //GAME DATA LOADED SET THE FLAG TO TRUE gameDataLoaded = true; }
private IEnumerator SaveLevelGameData(int level) { string address = Application.absoluteURL == string.Empty ? StaticDb.serverAddressEditor : Application.absoluteURL.TrimEnd('/'); //GET THE CORRECT LEVELMANAGER manager = SetLevelManager(); //GET GAMEDATA FROM THE MANAGER gameData = manager.GetGameData(); ////IF IS FIRST LAUNCH SET TO FALSE //if (gameData.firstLaunch) // gameData.firstLaunch = false; //SET LONG DATE VALUE gameData.longDate = gameData.date.ToFileTimeUtc(); //SET LEVEL INDEX gameData.levelIndex = level; //SET CAMERA ZOOM VALUE CinemachineVirtualCamera virtualCamera = FindObjectOfType <CinemachineVirtualCamera>(); gameData.cameraZoom = virtualCamera.m_Lens.OrthographicSize; Debug.Log(gameData.cameraZoom); //SET ALL THE serializableAiController foreach (TimeEvent timeEvent in gameData.timeEventList) { if (timeEvent.threat.aiController != null) { timeEvent.threat.serializableAiController = new SerializableAiController(timeEvent.threat.aiController); Debug.Log(timeEvent.threat.aiController); } //Debug.Log("FOREACH"); } //PARSE GAMEDATA INSTANCE INTO JSON string data = JsonUtility.ToJson(gameData, true); //CREATE NEW WWWFORM FOR SENDING DATA WWWForm formData = new WWWForm(); //ADD FIELD TO FORM formData.AddField("mode", "w"); formData.AddField("mainDataFolder", StaticDb.mainDataFolder); formData.AddField("playerFolder", StaticDb.player.folderName); formData.AddField("saveFolder", StaticDb.saveFolder); //formData.AddField("saveFileName", StaticDb.slotName + manager.GetGameData().indexSlot + StaticDb.slotExt); formData.AddField("saveFileName", StaticDb.gameSaveName + StaticDb.gameSaveExt); formData.AddField("saveContent", data); //UPLOAD JSON DATA FROM GAMEDATA CLASS using (UnityWebRequest www = UnityWebRequest.Post( Path.Combine(address, Path.Combine(StaticDb.phpFolder, StaticDb.playerSaveManagerScript)), formData)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log(www.downloadHandler.text); } } }
IEnumerator login() { WWWForm form = new WWWForm(); form.AddField("myField", "myData"); using ( UnityWebRequest www = UnityWebRequest.Post(Config.Control.urlLogin + "username="******"&password="******"", form)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { // Debug.Log (www.error); //error.text = www.downloadHandler.text; error.text = "Username atau Password Anda Salah"; loading.SetActive(false); } else { loading.SetActive(false); menulogin.SetActive(false); menuindentitas.SetActive(true); //Debug.Log(www.downloadHandler.text); //string dat = www.downloadHandler.text; JSONNode jsonData = JSON.Parse(System.Text.Encoding.UTF8.GetString(www.downloadHandler.data)); token = jsonData["data"]["token"]; id_peserta = jsonData["data"]["id_peserta"]; id_event = jsonData["data"]["id_event"]; id_game = jsonData["data"]["listGame"][0]["id_game"]; tokenInput.text = token; Debug.Log(jsonData); if (jsonData == null) { Debug.Log("ora ono"); } else { //int namaContoh = jsonData["attribute"]["nama"].Count; //string namaContoh = jsonData["attribute"]["nama"]["attribute"].ToString(); //string replaceNama = namaContoh.Replace("{", ""); //Debug.Log( "jumlah chil nama" +namaContoh); /* * for (int i = 0; i < code.Length; i++) * { * if (code[i] == "SFEA") * { * scene.Add("level1_tanoto"); * scene.Add("level2_tanoto"); * scene.Add("level3_tanoto"); * } * if (code[i] == "SFEB") * { * scene.Add("level4_tanoto"); * scene.Add("level5_tanoto"); * scene.Add("level6_tanoto"); * } * if (code[i] == "SFEC") * { * scene.Add("level7_tanoto"); * } * if (code[i] == "SFED") * { * scene.Add("level8_tanoto"); * } * if (code[i] == "SFEX") * { * scene.Add("level1_tanoto"); * scene.Add("level2_tanoto"); * scene.Add("level3_tanoto"); * scene.Add("level4_tanoto"); * scene.Add("level5_tanoto"); * scene.Add("level6_tanoto"); * scene.Add("level7_tanoto"); * scene.Add("level8_tanoto"); * } * } */ //======================================================================================================================= for (int i = 0; i < jsonData["data"]["listGame"].Count; i++) { for (int j = 0; j < game_id.Length; j++) { if (jsonData["data"]["listGame"][i]["id_game"] == game_id[j]) { if (jsonData["data"]["listGame"][i]["code_game"] == "SFEA") { scene.Add("level1_tanoto"); scene.Add("level2_tanoto"); scene.Add("level3_tanoto"); } if (jsonData["data"]["listGame"][i]["code_game"] == "SFEB") { scene.Add("level4_tanoto"); scene.Add("level5_tanoto"); scene.Add("level6_tanoto"); } if (jsonData["data"]["listGame"][i]["code_game"] == "SFEC") { scene.Add("level7_tanoto"); } if (jsonData["data"]["listGame"][i]["code_game"] == "SFED") { scene.Add("level8_tanoto"); } if (jsonData["data"]["listGame"][i]["code_game"] == "SFEX") { scene.Add("level1_tanoto"); scene.Add("level2_tanoto"); scene.Add("level3_tanoto"); scene.Add("level4_tanoto"); scene.Add("level5_tanoto"); scene.Add("level6_tanoto"); scene.Add("level7_tanoto"); scene.Add("level8_tanoto"); } } } } //============================================================================================================================ for (int i = 0; i <= jsonData["data"]["biodata"].Count - 1; i++) { //Debug.Log(" text string attribute" + i + " -" + jsonData["attribute"][i].ToString()); //EDIT AFIF //for(int j = 0; j <= jsonData["data"]["biodata"].Count - 1; j++) //{ if (jsonData["data"]["biodata"][i][2] == "text") { labelnya[i].text = jsonData["data"]["biodata"][i][1]; labelnya[i].gameObject.SetActive(true); labelnya[i].transform.Find("chillAttribute").GetComponent <Text>().text = jsonData["data"]["biodata"][i][0]; inputan_text[i].SetActive(true); //inputan_text[i].GetComponent<GridLayoutGroup>().cellSize= new Vector3(350, 100); inputan_text[i].transform.Find("InputField").gameObject.SetActive(true); inputan_text[i].transform.Find("InputField").GetComponent <InputField>().placeholder.GetComponent <Text>().text = "Wajib diisi"; inputan_text[i].transform.Find("DatePicker").gameObject.SetActive(false); } if (jsonData["data"]["biodata"][i][2] == "date") { labelnya[i].text = jsonData["data"]["biodata"][i][1]; labelnya[i].gameObject.SetActive(true); labelnya[i].transform.Find("chillAttribute").GetComponent <Text>().text = jsonData["data"]["biodata"][i][0]; inputan_text[i].SetActive(true); inputan_text[i].GetComponent <GridLayoutGroup>().cellSize = new Vector3(350, 200); inputan_text[i].transform.Find("InputField").gameObject.SetActive(false); inputan_text[i].transform.Find("DatePicker").gameObject.SetActive(true); } if (jsonData["data"]["biodata"][i][2] == "textarea") { labelnya[i].text = jsonData["data"]["biodata"][i][1]; labelnya[i].gameObject.SetActive(true); labelnya[i].transform.Find("chillAttribute").GetComponent <Text>().text = jsonData["data"]["biodata"][i][0]; inputan_text[i].SetActive(true); inputan_text[i].transform.Find("InputField").gameObject.SetActive(true); inputan_text[i].transform.Find("InputField").GetComponent <InputField>().lineType = InputField.LineType.MultiLineNewline; inputan_text[i].transform.Find("InputField").GetComponent <InputField>().placeholder.GetComponent <Text>().text = "Wajib diisi"; inputan_text[i].transform.Find("DatePicker").gameObject.SetActive(false); } if (jsonData["data"]["biodata"][i][2] == "dropdown") { Debug.Log("VALUE DROBDON" + jsonData["attribute"][i][3].Count); labelnya[i].text = jsonData["data"]["biodata"][i][1]; labelnya[i].gameObject.SetActive(true); labelnya[i].transform.Find("chillAttribute").GetComponent <Text>().text = jsonData["data"]["biodata"][i][0]; inputan_text[i].SetActive(true); inputan_text[i].transform.Find("Dropdown").gameObject.SetActive(true); inputan_text[i].transform.Find("InputField").gameObject.SetActive(false); inputan_text[i].transform.Find("DatePicker").gameObject.SetActive(false); var dropdown = inputan_text[i].transform.Find("Dropdown").GetComponent <Dropdown>(); dropdown.options.Clear();; for (int x = 0; x <= jsonData["data"]["biodata"][i][3].Count - 1; x++) { List <String> valueDropdown = new List <string>(); valueDropdown.Add(jsonData["data"]["biodata"][i][3][x]); foreach (var item in valueDropdown) { dropdown.options.Add(new Dropdown.OptionData() { text = item }); } //dropdown.options.Add(new Drop) } } } } } } }
private static void Upload(Store <AppState> store) { var token = UnityConnectSession.instance.GetAccessToken(); if (token.Length == 0) { CheckLoginStatus(store); return; } var path = store.state.shareState.zipPath; var title = store.state.shareState.title; var buildGUID = store.state.shareState.buildGUID; var baseUrl = getAPIBaseUrl(); var projectId = GetProjectId(); var formSections = new List <IMultipartFormSection>(); formSections.Add(new MultipartFormDataSection("title", title)); if (buildGUID.Length > 0) { formSections.Add(new MultipartFormDataSection("buildGUID", buildGUID)); } if (projectId.Length > 0) { formSections.Add(new MultipartFormDataSection("projectId", projectId)); } formSections.Add(new MultipartFormFileSection("file", File.ReadAllBytes(path), Path.GetFileName(path), "application/zip")); uploadRequest = UnityWebRequest.Post(baseUrl + uploadEndpoint, formSections); uploadRequest.SetRequestHeader("Authorization", $"Bearer {token}"); uploadRequest.SetRequestHeader("X-Requested-With", "XMLHTTPREQUEST"); var op = uploadRequest.SendWebRequest(); ConnectShareEditorWindow.StartCoroutine(updateProgress(store, uploadRequest)); op.completed += operation => { if (uploadRequest.isNetworkError || uploadRequest.isHttpError) { Debug.Log(uploadRequest.error); if (uploadRequest.error != "Request aborted") { store.Dispatch(new OnErrorAction { errorMsg = "Internal server error" }); } } else { var response = JsonUtility.FromJson <UploadResponse>(op.webRequest.downloadHandler.text); if (!string.IsNullOrEmpty(response.key)) { store.Dispatch(new QueryProgressAction { key = response.key }); } } }; }
public SketchfabRequest(string url, List <IMultipartFormSection> _multiPart) { _request = UnityWebRequest.Post(url, _multiPart); }
public IEnumerator Upload() { //loadingAnim.SetActive(true); posting_msg.SetActive(true); //string post_url = Mainurl + upload_image_API; string post_url = "https://www.skillmuni.in/wsmapi/api/PostPhotoUpload/TagPhotoUpload"; //Debug.Log(BitConverter.ToString(imageBytes)); string usertext = user_text.text; string plan = plan_title.text; string level = PlayerPrefs.GetInt("game_id").ToString(); string lati = PlayerPrefs.GetFloat("LAT").ToString(); string longi = PlayerPrefs.GetFloat("LONG").ToString(); string uid = PlayerPrefs.GetInt("UID").ToString(); string oid = PlayerPrefs.GetInt("OID").ToString(); for (int a = 0; a < Bigger_count; a++) { List <IMultipartFormSection> formData = new List <IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("UID", uid)); formData.Add(new MultipartFormDataSection("OID", oid)); formData.Add(new MultipartFormDataSection("EXTN", "png")); formData.Add(new MultipartFormFileSection("Media", post_image_byte[a], test.name, "image/png")); formData.Add(new MultipartFormDataSection("GCI", level)); formData.Add(new MultipartFormDataSection("Level", level_zone.ToString())); formData.Add(new MultipartFormDataSection("LATI", lati)); formData.Add(new MultipartFormDataSection("LONGI", longi)); formData.Add(new MultipartFormDataSection("DETAIL", User_text[a])); formData.Add(new MultipartFormDataSection("KEYINFO", User_plan[a])); UnityWebRequest www = UnityWebRequest.Post(post_url, formData); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); respose_text.text = www.downloadHandler.text; posting_msg.SetActive(false); statusmsg.text = "PLEASE TRY LATER!"; yield return(new WaitForSeconds(3f)); statusmsg.text = ""; imageBytes = null; statusmsg.gameObject.SetActive(false); } else { Debug.Log("Form upload complete! " + a); Debug.Log(www.downloadHandler.text); yield return(new WaitForSeconds(0.5f)); formData.Clear(); ////zone_handle.actionplan_score += 25; } } posting_msg.SetActive(false); //loadingAnim.SetActive(false); statusmsg.gameObject.SetActive(true); statusmsg.text = "PLAN SUCCESSFULLY GENERATED!"; yield return(new WaitForSeconds(2.5f)); statusmsg.text = ""; statusmsg.gameObject.SetActive(false); user_text.text = ""; plan_title.text = ""; reduce_plan.text = ""; reduce_text.text = ""; recycle_plan.text = ""; recycle_text.text = ""; User_text.Clear(); User_plan.Clear(); Bigger_count = 0; post_image_byte.Clear(); capturebtn1.gameObject.GetComponent <Image>().sprite = default_sprite; capturebtn2.gameObject.GetComponent <Image>().sprite = default_sprite; capturebtn3.gameObject.GetComponent <Image>().sprite = default_sprite; }
IEnumerator Upload() { WWWForm form = new WWWForm(); //Debug.Log("Uploaddddddd"); form.AddField("usuario", setUser); form.AddField("juego", setNivel); form.AddField("nivel", setDificultad); form.AddField("tiempo", setTiempo); form.AddField("scores", setScore); form.AddField("grado", setGrado); Debug.Log("DATOS"); Debug.Log(setUser); Debug.Log(setNivel); Debug.Log(setDificultad); Debug.Log(setTiempo); Debug.Log(setScore); Debug.Log(setGrado); Debug.Log("END DATOS"); UnityWebRequest www = UnityWebRequest.Post("https://herokudjangoappaqp.herokuapp.com/api/agregar/", form); yield return(www.SendWebRequest()); //Text_info.text = "Entreeeeeee" + setNivel; if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); TextInfo.text = "ERRRRRRROR " + grado; } else { //var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(www); MyClass myObject = new MyClass(); myObject = JsonUtility.FromJson <MyClass>(www.downloadHandler.text); //Text_info.text = "No LO se" + grado; string linkk = myObject.ayuda; if (myObject.resultado == "Aprendio.") { TextInfo.text = "Felicidades usted completo el nivel satisfactoriamente "; } if (myObject.resultado == "No Aprendio.") //else { TextInfo.text = "No logro completar los objetivos del nivel, para mejorar sus capacidades ingrese en el siguiente link: "; BtnLink.GetComponentInChildren <Text>().text = linkk; } //LinkBtn.GetComponentInChildren<Text>().text = //Aprender.text = myObject.ayuda; } }
public static IObservable <string> Post(string url, WWWForm content, IProgress <float> progress = null) { return(ObservableUnity.FromCoroutine <string>((observer, cancellation) => FetchText(UnityWebRequest.Post(url, content), observer, progress, cancellation))); }
IEnumerator Changepass(string password, string name) { string ChangepassUrl = "https://scivre.herokuapp.com/api/webapichangepass"; canvasLoad.SetActive(true); lblLoader.text = "Sending Request to webserver"; // first if checking internet connection ang web serve response pare if (Validation1.checkConnectionfail() == true) { errorfieldchange.text = "Error: Internet Connection"; canvasLoad.SetActive(false); } else { //Checking web server response WWWForm form = new WWWForm(); Debug.Log(password); form.AddField("password", password); form.AddField("name", name); using (UnityWebRequest www = UnityWebRequest.Post(ChangepassUrl, form)) { www.chunkedTransfer = false; yield return(www.SendWebRequest()); Debug.Log(www.error + " "); if (www.error != null) { errorfieldchange.text = "Error webserver request error: " + www.error; } else { Debug.Log("Response" + www.downloadHandler.text); Validation1.UserDetail userDetail = JsonUtility.FromJson <Validation1.UserDetail> (www.downloadHandler.text); //reponse details if (userDetail.status == 1) { lblLoader.text = "Password Successfully Updated"; yield return(new WaitForSeconds(3f)); errorfieldchange.text = userDetail.message; canvasLoad.SetActive(false); changePanel.SetActive(false); loginPanel.SetActive(true); } else { errorfieldchange.text = www.downloadHandler.text; changePanel.SetActive(false); } } } } }
IEnumerator UploadJPG() { // We should only read the screen buffer after rendering is complete yield return(new WaitForEndOfFrame()); // Create a texture the size of the screen, RGB24 format int width = Screen.width; int height = Screen.height; Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, true); // Read screen contents into the texture tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply(); Texture2D tex2 = new Texture2D(tex.width / 2, tex.height / 2, TextureFormat.RGB24, true); // Read screen contents into the texture tex2.SetPixels(tex.GetPixels(1)); tex2.Apply(); Texture2D tex3 = new Texture2D(tex2.width / 2, tex2.height / 2, TextureFormat.RGB24, true); // Read screen contents into the texture tex3.SetPixels(tex2.GetPixels(1)); tex3.Apply(); // Encode texture into PNG byte[] bytes = tex3.EncodeToPNG(); string timeStamp = idLogin.text + "_" + namaPemain.text + "_" + LevelMain.text + "_checkout_" + tnya.ToString(); // For testing purposes, also write to a file in the project folder //File.WriteAllBytes(Application.dataPath + "/../"+ timeStamp + ".jpeg", bytes); WWWForm form = new WWWForm(); //===========================================================================================================// //EDIT AFIF ALLGAME form.AddField("token", btn_manager_Magnet.Control.token); form.AddField("id_event", btn_manager_Magnet.Control.id_event); form.AddField("id_peserta", btn_manager_Magnet.Control.id_peserta); form.AddField("id_game", btn_manager_Magnet.Control.id_game); form.AddField("nama_hirarki", "level_5"); form.AddBinaryData("nama_file", bytes, timeStamp + ".jpeg"); //===========================================================================================================// // Upload to a cgi script UnityWebRequest w = UnityWebRequest.Post(Config.Control.urlImage, form); yield return(w.SendWebRequest()); if (w.isNetworkError || w.isHttpError) { Loading.SetActive(false); Debug.Log(w.error); } else { Loading.SetActive(false); if (btn_manager_Magnet.Control.sceneInt < btn_manager_Magnet.Control.scene.Count) { SceneManager.LoadScene(btn_manager_Magnet.Control.scene[btn_manager_Magnet.Control.sceneInt]); btn_manager_Magnet.Control.sceneInt++; } else { SceneManager.LoadScene("main_akhir_tanoto"); } } }
/// <summary> /// 取得 Google Excel 表單序號資料 /// </summary> private IEnumerator GetGoogleExcelLicense() { licenseInput = inputFieldLicense.text; btnLicenseInputOK.interactable = false; inputFieldLicense.interactable = false; WWWForm form = new WWWForm(); form.AddField("method", "取得序號"); form.AddField("sheetName", licenseInput); using (UnityWebRequest www = UnityWebRequest.Post(linkExcelGoogleAppScript, form)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { print("取得資料錯誤:" + www.error); } else { licenseInExcel = www.downloadHandler.text; // 取得 Excel 內的序號 ※第一列第一欄 } } if (licenseInExcel.Contains("免費序號")) { string countString = licenseInExcel.Remove(0, 4); int count = Convert.ToInt32(countString); print("免費序號" + count); groupFreeLicense.alpha = 1; if (count > 0) { count--; WWWForm formFreeCount = new WWWForm(); formFreeCount.AddField("method", "更新免費序號次數"); formFreeCount.AddField("sheetName", licenseInput); formFreeCount.AddField("countFree", count); using (UnityWebRequest www = UnityWebRequest.Post(linkExcelGoogleAppScript, formFreeCount)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { print("取得資料錯誤:" + www.error); } else { licenseInExcel = www.downloadHandler.text; // 取得 Excel 內的序號 ※第一列第一欄 } } print(licenseInExcel); } else { textFreeLicenseTip.text = "免費序號次數已使用完畢"; groupFreeLicense.blocksRaycasts = true; groupFreeLicense.interactable = true; } } else { bool licenseCheck = licenseInput == licenseInExcel; // 判定序號是否正確 goCorrect.SetActive(licenseCheck); // 正確 - 顯示與否 goWrong.SetActive(!licenseCheck); // 錯誤 - 顯示與否 } if (licenseInExcel == "免費序號次數更新成功") { textFreeLicenseTip.text = "免費序號使用成功"; groupFreeLicense.blocksRaycasts = true; groupFreeLicense.interactable = true; PlayerPrefs.SetInt("是否購買", 1); } goLicenseInput.SetActive(false); // 隱藏序號輸入欄位 inputFieldLicense.text = ""; btnLicenseInputOK.interactable = true; inputFieldLicense.interactable = true; }
public void Start() { #if !UNITY_WEBPLAYER #if !DOT_NET FileInfo info = new FileInfo(_localPath); byte[] file; if (info.Exists) { file = File.ReadAllBytes(_localPath); } else { file = System.Convert.FromBase64String(_localPath); } WWWForm postForm = new WWWForm(); postForm.AddField("sessionId", _sessionId); if (_peerCode != "") { postForm.AddField("peerCode", _peerCode); } postForm.AddField("uploadId", UploadId); postForm.AddField("fileSize", file.Length); postForm.AddBinaryData("uploadFile", file, _fileName); #if USE_WEB_REQUEST _request = UnityWebRequest.Post(_serverUrl, postForm); _request.SendWebRequest(); #else _request = new WWW(_serverUrl, postForm); #endif #else var requestMessage = new HttpRequestMessage() { RequestUri = new Uri(_serverUrl), Method = HttpMethod.Post }; var requestContent = new MultipartFormDataContent(); ProgressStream fileStream = new ProgressStream(new FileStream(_localPath, FileMode.Open, FileAccess.Read, FileShare.Read)); fileStream.BytesRead += BytesReadCallback; requestContent.Add(new StringContent(_sessionId), "sessionId"); if (_peerCode != "") { requestContent.Add(new StringContent(_peerCode), "peerCode"); } requestContent.Add(new StringContent(UploadId), "uploadId"); requestContent.Add(new StringContent(TotalBytesToTransfer.ToString()), "fileSize"); requestContent.Add(new StreamContent(fileStream), "uploadFile", _fileName); requestMessage.Content = requestContent; _cancelToken = new CancellationTokenSource(); Task <HttpResponseMessage> httpRequest = HttpClient.SendAsync(requestMessage, _cancelToken.Token); httpRequest.ContinueWith(async(t) => { await AsyncHttpTaskCallback(t); }); #endif Status = FileUploaderStatus.Uploading; if (_client.LoggingEnabled) { _client.Log("Started upload of " + _fileName); } _lastTime = DateTime.Now; #endif }
public IEnumerator _PostToServer(string rFileName) { while (!IsFileSaveComplete(rFileName + ".log")) { yield return(0); } var account = Module_Login.instance?.account; WWWForm postForm = new WWWForm(); var playerName = string.Empty; if (Module_Player.instance != null) { playerName = Module_Player.instance.roleInfo.roleId.ToString(); } var path = gameLogger.GetFullPath(rFileName); var contents = Util.LoadFile(path); if (contents != null && contents.Length > 0) { postForm.AddBinaryData("logFile", contents, $"{rFileName }_{playerName}.log"); } var request = UnityWebRequest.Post(WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA), postForm); request.SetRequestHeader("Content-Type", postForm.headers["Content-Type"]); request.SetRequestHeader("Authorization", BasicAuth(account?.acc_name ?? "null", "123456")); request.SetRequestHeader("X-Game-Identity", $"kzwg/{rFileName}"); request.timeout = 5; yield return(request.SendWebRequest()); if (request.isNetworkError) { Logger.LogWarning($"日志文件上传失败:{request.url}"); yield break; } Logger.LogWarning($"日志文件上传成功:{WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA)} 数据大小:{contents.Length}"); request.Dispose(); while (!IsFileSaveComplete(rFileName + ".gr")) { yield return(0); } postForm = new WWWForm(); path = GameRecorder.GetFullPath(rFileName); contents = Util.LoadFile(path); if (contents != null && contents.Length > 0) { postForm.AddBinaryData("grFile", contents, $"{rFileName }_{playerName}.gr"); } request = UnityWebRequest.Post(WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA), postForm); request.SetRequestHeader("Content-Type", postForm.headers["Content-Type"]); request.SetRequestHeader("Authorization", BasicAuth(account?.acc_name ?? "null", "123456")); request.SetRequestHeader("X-Game-Identity", $"kzwg/{rFileName}"); request.timeout = 5; yield return(request.SendWebRequest()); if (request.isNetworkError) { Logger.LogWarning($"录像文件上传失败:{request.url}"); yield break; } Logger.LogWarning($"录像文件上传成功:{WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA)} 数据大小:{contents.Length}"); request.Dispose(); }
IEnumerator DoLogin() { //cheat if (email.text == "") { errorMsg.text = "Email Field Cannot be Empty"; } else if (password.text == "") { errorMsg.text = "Password Field Cannot be Empty"; } else { loader = Instantiate(loaderPrefab, loaderPrefab.transform.position, loaderPrefab.transform.rotation) as GameObject; WWWForm form = new WWWForm(); form.AddField("email", email.text); form.AddField("password", password.text); //UnityWebRequest www = UnityWebRequest.Post("http://182.18.139.143/WITSCLOUD/DEVELOPMENT/dartweb/index.php/api/login", form); UnityWebRequest www = UnityWebRequest.Post("https://dartbet.io/index.php/Api/login", form); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); Destroy(loader); } else { Debug.Log("Form upload complete!"); StringBuilder sb = new StringBuilder(); foreach (System.Collections.Generic.KeyValuePair <string, string> dict in www.GetResponseHeaders()) { sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n"); } // Print Headers Debug.Log("header" + sb.ToString()); // Print Body Debug.Log("Body:" + www.downloadHandler.text); JSONNode loginResponse = SimpleJSON.JSON.Parse(www.downloadHandler.text); if (loginResponse["status"].ToString() == "true") { GameManager.userInfo = JsonUtility.FromJson <UserInfo>(loginResponse["userData"].ToString()); GameManager.userToken = GameManager.userInfo.token; Debug.Log("user token: " + GameManager.userToken); JSONNode userDataResponse = ServerCalls.GetUserInfo(); Debug.Log("userDataResponse:: " + userDataResponse.ToString()); string response = userDataResponse["status"].Value; if (response == "Success") { if (saveUser) { PlayerPrefs.SetString("SAVED_EMAIL", email.text); PlayerPrefs.SetString("SAVED_PASSWORD", password.text); PlayerPrefs.Save(); } GameSceneManager.LoadScene("HomeScreen"); } else { Destroy(loader); errorMsg.text = userDataResponse["message"].ToString(); } } else { Destroy(loader); errorMsg.text = loginResponse["message"].ToString(); } } } }
public static IEnumerator SendHttpMsg(string url, string method, Dictionary <string, object> param, HttpMsgCallback callback) { if (string.Compare(method, "get", true) == 0) { UnityWebRequest getTW = null; if (param == null || param.Count == 0) { getTW = UnityWebRequest.Get(url); } else { StringBuilder strParams = new StringBuilder(); bool first = true; foreach (KeyValuePair <string, object> val in param) { if (first == false) { strParams.Append("&"); } strParams.AppendFormat("{0}={1}", val.Key, val.Value.ToString()); first = false; } getTW = UnityWebRequest.Get(string.Format("{0}?{1}", url, strParams.ToString())); } getTW.method = UnityWebRequest.kHttpVerbGET; getTW.timeout = TimeOut; yield return(getTW.SendWebRequest()); if (getTW.isDone) { if (getTW.error != null) { callback(getTW.error, null); } else { callback(null, getTW.downloadHandler.text); } } else { callback("sendHttpMsg get not done", null); } } else if (string.Compare(method, "post", true) == 0) { WWWForm postForm = new WWWForm(); if (param != null) { foreach (KeyValuePair <string, object> val in param) { postForm.AddField(val.Key, val.Value.ToString()); } } UnityWebRequest postTW = UnityWebRequest.Post(url, postForm); yield return(postTW.SendWebRequest()); if (postTW.isDone) { if (postTW.error != null) { callback(postTW.error, null); } else { callback(null, postTW.downloadHandler.text); } } else { callback("sendHttpMsg get not done", null); } } else { throw new Exception("HttpUtils->SendHttpMsg->not support " + method); } }
//Authorization set-up public static string GetTwitterAccessToken(string consumerKey, string consumerSecret) { //Convert the consumer key and secret strings into a format to be added to our header string URL_ENCODED_KEY_AND_SECRET = Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret)); byte[] body; body = Encoding.UTF8.GetBytes("grant_type=client_credentials"); Dictionary <string, string> headers = new Dictionary <string, string>(); headers["Authorization"] = "Basic " + URL_ENCODED_KEY_AND_SECRET; WWWForm form = new WWWForm(); form.AddField("grant_type", "client_credentials"); UnityWebRequest request = UnityWebRequest.Post("https://api.twitter.com/oauth2/token", form); request.SetRequestHeader("Authorization", headers["Authorization"]); request.SendWebRequest(); while (!request.isDone) { Debug.Log("Get the f*****g token"); } if (request.error != null) { Debug.Log("Error my guy: " + request.error); } else { string output = request.downloadHandler.text.Replace("{\"token_type\":\"bearer\",\"access_token\":\"", ""); output = output.Replace("\"}", ""); Debug.Log("Got emmmm: " + output); return(output); } Debug.Log("Woowwwww: " + request.downloadHandler.text); ////Send a request to the Twitter API for an access token //WWW web = new WWW("https://api.twitter.com/oauth2/token", body, headers); //while (!web.isDone) //{ // Debug.Log("Retrieving access token..."); //} //if (web.error != null) //{ // //If there was a problem with the request, output the error to the debug log // Debug.Log("Web error: " + web.error); // Debug.Log("Headers: " + web.text); //} //else //{ // Debug.Log("Access token retrieved successfully"); // //Format string response into something more useable. // string output = web.text.Replace("{\"token_type\":\"bearer\",\"access_token\":\"", ""); // output = output.Replace("\"}", ""); // return output; //} //In the event of failure return(null); }
public UnityWebRequest getWWW(bool isImage = false) { refreshHeaders(); UnityWebRequest www = null; if (requestType == RequestType.GET) { //Uri uri = new Uri(url); //TODO Add the restauranyt Parameters string murl = url; bool first = true; foreach (var key in body.Keys) { if (first) { murl += "?"; first = false; } else { murl += "&"; } murl += key + "=" + body[key]; } if (requestType == RequestType.GET) { if (isImage) { www = UnityWebRequestTexture.GetTexture(murl); } else { www = UnityWebRequest.Get(murl); } } else if (requestType == RequestType.DELETE) { www = UnityWebRequest.Delete(murl); } } else { if (body == null) { if (requestType == RequestType.POST) { www = UnityWebRequest.Post(url, jsonBody.ToString().Trim()); } else if (requestType == RequestType.PUT) { www = UnityWebRequest.Put(url, jsonBody.ToString()); } www.SetRequestHeader("content-type", "application/json"); } else { if (requestType == RequestType.POST) { var form = new WWWForm(); foreach (var key in body.Keys) { form.AddField(key, body[key]); } www = UnityWebRequest.Post(url, form); } else if (requestType == RequestType.PUT) { var json = JSON.Parse("{}"); foreach (var key in body.Keys) { json[key] = body[key]; } www = UnityWebRequest.Put(url, json.ToString()); www.SetRequestHeader("content-type", "application/json"); } } } foreach (string key in header.Keys) { www.SetRequestHeader(key, header[key]); } return(www); }
private IEnumerator ProcessRequestQueue() { // yield AFTER we increment the connection count, so the Send() function can return immediately _activeConnections += 1; #if UNITY_EDITOR if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) { yield return(null); } #else yield return(null); #endif while (_requests.Count > 0) { Request req = _requests.Dequeue(); if (req.Cancel) { continue; } string url = URL; if (!string.IsNullOrEmpty(req.Function)) { url += req.Function; } StringBuilder args = null; foreach (var kp in req.Parameters) { var key = kp.Key; var value = kp.Value; if (value is string) { value = UnityWebRequest.EscapeURL((string)value); } else if (value is byte[]) { value = Convert.ToBase64String((byte[])value); } else if (value is Int32 || value is Int64 || value is UInt32 || value is UInt64 || value is float) { value = value.ToString(); } else if (value is bool) { value = value.ToString().ToLower(); } else if (value is DateTime?) { value = String.Format("{0:yyyy-MM-ddThh:mm:ssZ}", value);//yyyy-MM-ddthh:mm:ssz } else if (value != null) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported parameter value type {0}", value.GetType().Name); } else { Log.Error("RESTConnector.ProcessRequestQueue()", "Parameter {0} value is null", key); } if (args == null) { args = new StringBuilder(); } else { args.Append("&"); } args.Append(key + "=" + value); } if (args != null && args.Length > 0) { url += "?" + args.ToString(); } AddHeaders(req.Headers); Response resp = new Response(); DateTime startTime = DateTime.Now; UnityWebRequest unityWebRequest = null; if (req.Forms != null || req.Send != null) { // POST and PUT with data if (req.Forms != null) { if (req.Send != null) { Log.Warning("RESTConnector", "Do not use both Send & Form fields in a Request object."); } WWWForm form = new WWWForm(); try { foreach (var formData in req.Forms) { if (formData.Value.IsBinary) { form.AddBinaryData(formData.Key, formData.Value.Contents, formData.Value.FileName, formData.Value.MimeType); } else if (formData.Value.BoxedObject is string) { form.AddField(formData.Key, (string)formData.Value.BoxedObject); } else if (formData.Value.BoxedObject is int) { form.AddField(formData.Key, (int)formData.Value.BoxedObject); } else if (formData.Value.BoxedObject != null) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported form field type {0}", formData.Value.BoxedObject.GetType().ToString()); } } foreach (var headerData in form.headers) { req.Headers[headerData.Key] = headerData.Value; } } catch (Exception e) { Log.Error("RESTConnector.ProcessRequestQueue()", "Exception when initializing WWWForm: {0}", e.ToString()); } unityWebRequest = UnityWebRequest.Post(url, form); } else if (req.Send != null) { unityWebRequest = new UnityWebRequest(url, req.HttpMethod) { uploadHandler = (UploadHandler) new UploadHandlerRaw(req.Send) }; unityWebRequest.SetRequestHeader("Content-Type", "application/json"); } } else { // GET, DELETE and POST without data unityWebRequest = new UnityWebRequest { url = url, method = req.HttpMethod }; if (req.HttpMethod == UnityWebRequest.kHttpVerbPOST) { unityWebRequest.SetRequestHeader("Content-Type", "application/json"); } } foreach (KeyValuePair <string, string> kvp in req.Headers) { unityWebRequest.SetRequestHeader(kvp.Key, kvp.Value); } unityWebRequest.downloadHandler = new DownloadHandlerBuffer(); if (req.DisableSslVerification == true) { unityWebRequest.certificateHandler = new AcceptAllCertificates(); } else { unityWebRequest.certificateHandler = null; } #if UNITY_2017_2_OR_NEWER unityWebRequest.SendWebRequest(); #else www.Send(); #endif #if ENABLE_DEBUGGING Log.Debug("RESTConnector", "URL: {0}", url); #endif // wait for the request to complete. float timeout = Mathf.Max(Constants.Config.Timeout, req.Timeout); while (!unityWebRequest.isDone) { if (req.Cancel) { break; } if ((DateTime.Now - startTime).TotalSeconds > timeout) { break; } if (req.OnUploadProgress != null) { req.OnUploadProgress(unityWebRequest.uploadProgress); } if (req.OnDownloadProgress != null) { req.OnDownloadProgress(unityWebRequest.downloadProgress); } #if UNITY_EDITOR if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) { yield return(null); } #else yield return(null); #endif } if (req.Cancel) { continue; } bool bError = false; IBMError error = null; if (!string.IsNullOrEmpty(unityWebRequest.error)) { switch (unityWebRequest.responseCode) { case HTTP_STATUS_OK: case HTTP_STATUS_CREATED: case HTTP_STATUS_ACCEPTED: bError = false; break; default: bError = true; break; } string errorMessage = GetErrorMessage(unityWebRequest.downloadHandler.text); error = new IBMError() { Url = url, StatusCode = unityWebRequest.responseCode, ErrorMessage = errorMessage, Response = unityWebRequest.downloadHandler.text, ResponseHeaders = unityWebRequest.GetResponseHeaders() }; if (bError) { Log.Error("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, unityWebRequest.responseCode, unityWebRequest.error, string.IsNullOrEmpty(unityWebRequest.downloadHandler.text) ? "" : unityWebRequest.downloadHandler.text); } else { Log.Warning("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, unityWebRequest.responseCode, unityWebRequest.error, string.IsNullOrEmpty(unityWebRequest.downloadHandler.text) ? "" : unityWebRequest.downloadHandler.text); } } if (!unityWebRequest.isDone) { Log.Error("RESTConnector.ProcessRequestQueue()", "Request timed out for URL: {0}", url); bError = true; } // generate the Response object now.. if (!bError) { resp.Success = true; resp.Data = unityWebRequest.downloadHandler.data; resp.HttpResponseCode = unityWebRequest.responseCode; } else { resp.Success = false; resp.Error = error; } resp.Headers = unityWebRequest.GetResponseHeaders(); resp.ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds; // if the response is over a threshold, then log with status instead of debug if (resp.ElapsedTime > LogResponseTime) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Request {0} completed in {1} seconds.", url, resp.ElapsedTime); } if (req.OnResponse != null) { req.OnResponse(req, resp); } unityWebRequest.Dispose(); } // reduce the connection count before we exit. _activeConnections -= 1; yield break; }
IEnumerator Loop() { while (true) { yield return(new WaitForSeconds(1f)); WWWForm form = new WWWForm(); form.AddField("hash", key); form.AddField("id", deviceid); form.AddField("lat", Input.location.lastData.latitude.ToString()); form.AddField("lon", Input.location.lastData.longitude.ToString()); UnityWebRequest www = UnityWebRequest.Post(url, form); yield return(www.SendWebRequest()); if (string.IsNullOrEmpty(www.error)) { string[] coords = www.downloadHandler.text.Split('\n'); var list = new List <Vector2d>(); bool poi = false; foreach (string coord in coords) { Debug.Log(coord); } foreach (var c in coords) { if (poi) { if (c == null || c.Length < 4) { continue; } string[] data = c.Split(','); // data[0] = id // data [1] = url // data[2,3] = lat, lon string id = data[0]; string imgUrl = data[1]; if (markerIds.Contains(id)) { continue; } //Debug.Log(data[2] + " " + data[3] + " " + markerList[index]); StartCoroutine(SpawnMarker(imgUrl, id, new Vector2d(double.Parse(data[2]), double.Parse(data[3])))); } else { if (c != null && c.StartsWith("poi")) { poi = true; continue; } if (c == null || c.Length < 4) { continue; } string[] data = c.Split(','); list.Add(new global::Mapbox.Utils.Vector2d(double.Parse(data[0]), double.Parse(data[1]))); } } latLon = list.ToArray(); } int i = 0; for (; i < latLon.Length && i < players.Length; ++i) { players[i].gameObject.SetActive(true); players[i].localPosition = map.GeoToWorldPosition(latLon[i], true); } for (; i < players.Length; ++i) { players[i].gameObject.SetActive(false); } } }
private static void SendHeartbeat(bool fromSave = false) { if (_debug) { Debug.Log("<WakaTime> Sending heartbeat..."); } var currentScene = EditorSceneManager.GetActiveScene().path; var file = currentScene != string.Empty ? Path.Combine(Application.dataPath, currentScene.Substring("Assets/".Length)) : string.Empty; var heartbeat = new Heartbeat(file, fromSave); if ((heartbeat.time - _lastHeartbeat.time < HEARTBEAT_COOLDOWN) && !fromSave && (heartbeat.entity == _lastHeartbeat.entity)) { if (_debug) { Debug.Log("<WakaTime> Skip this heartbeat"); } return; } var heartbeatJSON = JsonUtility.ToJson(heartbeat); var request = UnityWebRequest.Post(URL_PREFIX + "users/current/heartbeats?api_key=" + _apiKey, string.Empty); request.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(heartbeatJSON)); request.SetRequestHeader("Content-Type", "application/json"); request.SendWebRequest().completed += operation => { if (request.downloadHandler.text == string.Empty) { //Debug.LogWarning( // "<WakaTime> Network is unreachable. Consider disabling completely if you're working offline"); return; } if (_debug) { Debug.Log("<WakaTime> Got response\n" + request.downloadHandler.text); } Response <HeartbeatResponse> response; try { response = JsonUtility.FromJson <Response <HeartbeatResponse> >( request.downloadHandler.text); } catch (ArgumentException) { return; } if (response.error != null) { if (response.error == "Duplicate") { if (_debug) { Debug.LogWarning("<WakaTime> Duplicate heartbeat"); } } else { Debug.LogError( "<WakaTime> Failed to send heartbeat to WakaTime!\n" + response.error); } } else { if (_debug) { Debug.Log("<WakaTime> Sent heartbeat!"); } _lastHeartbeat = response.data; } }; }
//로비화면에서 필요한 데이터만 로그인 유저 테이블을 참조하여 가져온다. IEnumerator S2C_UserData() { //로그인한 Email 정보를 가져온다. string _loginID = m_InfoManager.m_email; //HTTP통신을 할 대상 주소 string url = "49.247.131.35/S2C_UserData.php"; WWWForm myForm = new WWWForm(); myForm.AddField("email", _loginID); UnityWebRequest uwr = UnityWebRequest.Post(url, myForm); //서버에 문서를 요청한다. 그리고 반환되면 yield return 뒤에 구문이 실행된다. yield return(uwr.SendWebRequest()); //반환에서 네트워크 에러가 발생했다면 if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); yield break; } //정상적으로 반환값이 왔다면 else { //서버로부터 JSON형태의 메세지를 받는다. string jsonMessage = uwr.downloadHandler.text; //파싱할수있는 JOBJect 형태로 변환한다. JObject jobject = JObject.Parse(jsonMessage); //==================================================================================닉네임 string _nickname = (string)jobject["m_nickname"]; //==================================================================================차 string _carname = (string)jobject["m_car"]; string _carwheel = (string)jobject["m_wheel"]; string _carwing = (string)jobject["m_wing"]; GameObject memberCar; memberCar = Instantiate(Resources.Load("Car/" + _carname), new Vector3(0, 0, 0), Quaternion.identity) as GameObject; memberCar.transform.SetParent(m_rotateObjectParent.transform, false); memberCar.transform.localScale = new Vector3(1.6f, 1.6f, 1.6f); //==================================================================================바퀴 MeshRenderer[] _wheelList = memberCar.transform.Find("Wheel_Mesh").GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer _wheel in _wheelList) { _wheel.material = Resources.Load <Material>("Wheel/" + _carwheel); } //==================================================================================날개 memberCar.transform.Find(_carwing).gameObject.SetActive(true); //로비화면에서 로그인한 회원의 닉네임과 함께 인사말을 날린다. m_hello.text = _nickname + "님 안녕하세요!"; } }
//차고화면에서 필요한 로그인 유저가 보유한 모든 차량을 가져온다. 그리고 스크롤뷰에 차버튼을 만든다. IEnumerator S2C_WingList_All() { //HTTP통신을 할 대상 주소 string url = "49.247.131.35/S2C_WingList_All.php"; //====================================================================================클라이언트->서버 보낼 데이터 //로그인한 Email 정보를 가져온다. string _loginID = m_InfoManager.m_email; WWWForm myForm = new WWWForm(); myForm.AddField("email", _loginID); //============================================================================================================= UnityWebRequest uwr = UnityWebRequest.Post(url, myForm); //서버에 문서를 요청한다. 그리고 반환되면 yield return 뒤에 구문이 실행된다. yield return(uwr.SendWebRequest()); //반환에서 네트워크 에러가 발생했다면 if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); yield break; } //정상적으로 반환값이 왔다면 else { //서버로부터 JSON형태의 메세지를 받는다. string jsonMessage = uwr.downloadHandler.text; //파싱할수있는 JOBJect 형태로 변환한다. JObject jobject = JObject.Parse(jsonMessage); //==================================================================================회원정보 //회원 닉네임 정보 불러온다. string _nickname = (string)jobject["m_nickname"]; m_memberMoney.text = (string)jobject["m_money"]; //==================================================================================차 JArray _wings = (JArray)jobject["m_wing"]; _carcarAssetname = (string)jobject["m_car"]; _carwheelAssetname = (string)jobject["m_wheel"]; //널값 예외처리는 꼮 해준다. if (_wings != null) { //유저가 소지 하고있는 차는 1개이상이다. for (int i = 0; i < _wings.Count; i++) { //해당 차 버튼(차고화면에서 밑에 메뉴바의 스크롤뷰 안에 횡으로 생성된다.)을 생성한다. GameObject _CarButton = Instantiate(m_pref_carbutton, new Vector3(0, 0, 0), Quaternion.identity); //=======================================================차버튼에 필요한 정보들을 셋팅한다.============================================================== //버튼 최상 부모의 이름을 차이름으로 설정하여 어떤차를 클릭했는지 알고, 바로 경로에서 3D 모델을 불러올수있도록 구상 _CarButton.gameObject.name = (string)_wings[i]["m_assetname"]; //차 버튼 1번째는 선택됬을때 표시할 이미지 이다. //ChangeToSelectCarButton()에서 사용중 //차버튼 2번재 텍스트창에 차이름을 표시해준다. _CarButton.transform.GetChild(2).GetComponent <Text>().text = (string)_wings[i]["m_name"]; //차버튼 3번재 텍스트창에 차구매여부를 표시해준다. 이것을 기반으로 차 구매하기 버튼이 뜬다. _CarButton.transform.GetChild(3).GetComponent <Text>().text = (string)_wings[i]["m_buy"]; //구매한 차라면 if (_CarButton.transform.GetChild(3).GetComponent <Text>().text == "1") { //차버튼 밑 0번째는 로고를 넣어준다. _CarButton.transform.GetChild(0).GetComponent <Image>().sprite = Resources.Load <Sprite>("Images/Wing/" + (string)_wings[i]["m_assetname"]); } //구매한 차가 아니면 else { //차버튼 밑 0번째는 자물쇠를 넣어준다. _CarButton.transform.GetChild(0).GetComponent <Image>().sprite = Resources.Load <Sprite>("Images/lock"); } //차버튼 밑의 네번재 텍스트창에 차 가격을 표시해준다. _CarButton.transform.GetChild(4).GetComponent <Text>().text = (string)_wings[i]["m_price"]; //차고 하단 메뉴 스크롤뷰 자식으로 넣어준다.(그래야지 스크롤뷰안에 아이템으로 움직인다.) _CarButton.transform.SetParent(m_pref_carbutton_ScrollView.transform, false); //=======================================================회전 오브젝트에 필요한 정보를 셋팅한다.============================================================== //현재 착용중이라면 차고 회전오브젝트에 생성해준다. if ((int)_wings[i]["m_equip"] == 1) { m_now_carbutton = _CarButton; m_selectButtonName = m_now_carbutton.gameObject.name; //장착중인차는 장착중이라고 차버튼에 표시를 해준다. ChangeToSelectCarButtonImage(null, m_now_carbutton); //==================================================================================차 m_rotateCarModel = Instantiate(Resources.Load("Car/" + _carcarAssetname), new Vector3(0, 0, 0), Quaternion.identity) as GameObject; m_rotateCarModel.transform.SetParent(m_rotateObject.transform, false); m_rotateCarModel.transform.localScale = new Vector3(1.6f, 1.6f, 1.6f); MeshRenderer[] _wheelList = m_rotateCarModel.transform.Find("Wheel_Mesh").GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer _wheel in _wheelList) { _wheel.material = Resources.Load <Material>("Wheel/" + _carwheelAssetname); } //==================================================================================날개 m_rotateCarModel.transform.Find((string)_wings[i]["m_assetname"]).gameObject.SetActive(true); //==================================================================================================================================================== //화면 상단 이름 셋팅 m_carname_Object.transform.GetChild(0).GetComponent <Image>().sprite = Resources.Load <Sprite>("Images/Wing/" + (string)_wings[i]["m_assetname"]); m_carname_Object.transform.GetChild(1).GetComponent <Text>().text = (string)_wings[i]["m_name"]; m_carname_Object.transform.GetChild(2).GetComponent <Text>().text = (string)_wings[i]["m_price"]; m_carname_Object.transform.GetChild(2).gameObject.SetActive(false); m_carname_Object.transform.GetChild(3).gameObject.SetActive(true); } } } } //스탯 받아와서 출력해주어야한다. StartCoroutine(S2C_Stat(_carcarAssetname, _carwheelAssetname, m_now_carbutton.name)); }//Receive_Login_AllCar
[SerializeField] private List <ScoreData> leaderboards; // For Testing public bool Inspect() { var changed = false; pegi.nl(); "Player Name".edit(90, ref playerName).nl(ref changed); if (sortedLeaderboard.Count > 1 && "Sort Leaderboard".Click(ref changed)) { sortedLeaderboard.Sort((s1, s2) => s2.GetScore() - s1.GetScore()); } if (icon.Save.Click("Save Game State Data Locally")) { Save(); } if (icon.Load.ClickUnFocus("Load Game State Data from Persistant path")) { Load(); } if (icon.Folder.Click("Open Save data folder")) { FileExplorerUtils.OpenPersistentFolder(cfg.savedGameFolderName); } pegi.nl(); "Leaderboard".edit_List(ref sortedLeaderboard).nl(ref changed); #if UNITY_EDITOR if ("Json leaderboard test".enter(ref inspectedSection, 0).nl()) { "Score Json File Test".edit(ref test_Json).changes(ref changed); if (test_Json && icon.Create.ClickUnFocus("Try extract scoreboard from json")) { var filePath = AssetDatabase.GetAssetPath(test_Json); JsonUtility.FromJsonOverwrite(File.ReadAllText(filePath), this); } pegi.nl(); "Score Json string Test".edit(ref jsonTestString).changes(ref changed); if (!jsonTestString.IsNullOrEmpty() && icon.Create.ClickUnFocus("Read Json data from string").nl(ref changed)) { JsonUtility.FromJsonOverwrite(jsonTestString, this); } pegi.nl(); "Tmp Scores".edit_List(ref leaderboards).nl(ref changed); if (!leaderboards.IsNullOrEmpty()) { if ("Add Scores to leadeboard".ClickUnFocus("Will add the highest scores").nl()) { foreach (var scoreData in sortedLeaderboard) { var duplicant = leaderboards.GetByIGotName(scoreData.name); if (duplicant != null) { scoreData.UpdateScore(duplicant.GetScore()); leaderboards.Remove(duplicant); } } sortedLeaderboard.AddRange(leaderboards); leaderboards.Clear(); sortedLeaderboard.Sort((s1, s2) => s2.GetScore() - s1.GetScore()); } } } pegi.nl(); #endif if ("HTTP request test".enter(ref inspectedSection, 1).nl()) { "Server URL: ".edit(70, ref serverURL).nl(ref changed); if (!lastResult.IsNullOrEmpty()) { "Last Result: {0}".F(lastResult).nl(); } if (request != null) { if (request.isDone) { "Downloading done".nl(); if ("Read Data".Click()) { var wr = request.webRequest; if (wr.isNetworkError) { lastResult = wr.error; } else { lastResult = wr.downloadHandler.text; JsonUtility.FromJsonOverwrite(lastResult, this); if (lastResult.Length > 100) { lastResult = lastResult.Substring(0, 100) + "..."; } } request = null; } } else { "Request is processing: {0}%".F(Mathf.FloorToInt(request.progress * 100)).nl(); } } else { "Request Field".edit(ref requestField).nl(ref changed); "Request Value".edit(ref requestValue).nl(ref changed); if ("Post Request".Click()) { WWWForm form = new WWWForm(); form.AddField(requestField, requestValue); form.AddField("leaderboard_version", leaderboardVersion); UnityWebRequest wwwSignin = UnityWebRequest.Post(serverURL, form); request = wwwSignin.SendWebRequest(); } } } return(changed); }