Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using SimpleJson;
- using UnityEngine.Networking;
- [System.Serializable]
- public class UserData
- {
- public string user;
- public int score;
- }
- public class Test_API : MonoBehaviour {
- void Update()
- {
- if (Input.GetKeyUp(KeyCode.Space))
- {
- TaskOnClick("JohnDoe", 1337);
- }
- }
- // POST DATA
- IEnumerator WaitForWWW(WWW www)
- {
- yield return www;
- string txt = "";
- if (string.IsNullOrEmpty(www.error))
- txt = www.text; //text of success
- else
- txt = www.error; //error
- Debug.Log(txt);
- }
- void TaskOnClick(string user, int score)
- {
- StartCoroutine(PostRequest("http://myAwesomeScore/scoreboard/?format=json", user, score));
- }
- IEnumerator PostRequest(string url, string user, int score)
- {
- UserData user = new UserData();
- user.user = user;
- user.score = score;
- string bodyJsonString = JsonUtility.ToJson(user);
- Debug.Log("Data is: \n" + bodyJsonString);
- var request = new UnityWebRequest(url, "POST");
- byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(bodyJsonString);
- request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
- request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
- request.SetRequestHeader("Content-Type", "application/json");
- request.SetRequestHeader("Accept", "application/json");
- yield return request.SendWebRequest();
- Debug.Log("Response: " + request.downloadHandler.text);
- }
- void onRequestFinished(HTTPRequest req, HTTPResponse resp)
- {
- Debug.Log("Request Finished! Text received: " + resp.DataAsText);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement