Skip to content

Instantly share code, notes, and snippets.

@eaa3
Created May 26, 2018 13:37
Show Gist options
  • Select an option

  • Save eaa3/12fb0c5fe1eb80026d080d9659f1e924 to your computer and use it in GitHub Desktop.

Select an option

Save eaa3/12fb0c5fe1eb80026d080d9659f1e924 to your computer and use it in GitHub Desktop.
Send JSON file with Unity WebRequest
{"data": {"wrist": [100, 59, 90, 81, 56, 55, 40, 150],
"elbow": [2,20,2,2,10,0,10,500],
"shoulder": [28, 48, 200, 19, 96, 27, 100, 10],
"stats": {"averageSpeed":2.2580063343048097,"positionalError":0.6527959108352661,"timeElapsed":0.1699676513671875}
},
"description" : "10th test reach the target rehabilitation exercise",
"username" : "john2",
"password" : "123456"
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine;
using System.Text;
public class SendJSON : MonoBehaviour
{
private static string BASE_URL = "http://127.0.0.1:8000/healthprofile"; //http://healthbookdemo.herokuapp.com/healthprofile
private static string UPLOAD_JSON_URL = BASE_URL+"/eat_data/";
void Start()
{
string jsonString = loadJson("data.json");
Debug.Log("JSON to send: " + jsonString);
StartCoroutine(Upload(jsonString));
}
string loadJson(string filename){
string jsonString = System.IO.File.ReadAllText(filename);
return jsonString;
}
IEnumerator Upload(string jsonString) {
byte[] jsonBytes = Encoding.ASCII.GetBytes(jsonString);
UnityWebRequest jsonRequest = UnityWebRequest.Put(UPLOAD_JSON_URL, jsonBytes);
jsonRequest.SetRequestHeader("referer", UPLOAD_JSON_URL);
jsonRequest.SetRequestHeader("Content-Type", "text/json");
yield return jsonRequest.SendWebRequest();
if (jsonRequest.isNetworkError || jsonRequest.isHttpError)
{
Debug.Log("Response Code " + jsonRequest.responseCode);
Debug.Log(jsonRequest.error);
Debug.Log(jsonRequest.downloadHandler.text);
}
else
{
Debug.Log("Form upload complete!");
Debug.Log("Response Code " + jsonRequest.responseCode);
Debug.Log(jsonRequest.downloadHandler.text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment