Simple REST Client for Unity

Simple REST Utility for Unity

History:

Recently I needed a script though which I could easily get and send data to a REST Server. I picked my fav environment: MEAN. using Yeoman, I quickly implemented a simplistic REST Server, which will serve all data for my Unity WebPlayer Build. So here goes my take on a simple REST Utility for Unity.

NOTE:

Since UNity 5.3, the in-built REST client, httpwebrequest is really good and hence, you won’t be needing this tool at all. For below versions, you can use this code.

Unity has the wonderful WWW utility through which we can GET or POST data to/from any REST Server. After stumbling upon further, I found a StackOverflow post for a Simple GET/POST Wrapper for REST Utility for Unity.

I tweaked it a little ( added Callbacks instead of directly returning values) and use din my projects and it worked like a charm. And yes, for those who were concerned if it will work for WebBuilds, well, Yes, it works. I have Tested it.
The following is the code:

LIBRARY CODE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// file : DB.cs ( put this in Plugins Folder)


using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Object = System.Object;

///
/// Class D3VRest. A Wrapper class for simple and efficient REST API calls
///


namespace D3VRestWrapper
{
class D3VRest : MonoBehaviour
{
void Start() { }

///
/// Gets JSON data from the specified URL.
///

/// The URL.
/// The callback.
public void GET(string url, System.Action Callback = null)
{
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www, Callback));
}

///
/// Gets a texture form the specified URL.
///

/// The URL.
/// The callback.
public void GETTexture(string url, System.Action Callback = null)
{
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www, Callback, true));
}

///
/// GETs an asset from Asset Bundle
///

/// The Url to fetch the Asset from
/// Asset Name
/// The Callback that contains the GameObject as its parameter
public void GETAsset(string url, string AssetName, System.Action Callback = null)
{
StartCoroutine(WaitForAsset(url, AssetName, Callback));
}


///
/// Posts a Form data to the specified URL.
///

/// The URL.
/// The post.
/// The callback.
/// UnityEngine.WWW.
public WWW POST(string url, Dictionary<string, string> post, System.Action Callback = null)
{
WWWForm form = new WWWForm();
foreach (KeyValuePair post_arg in post)
{
form.AddField(post_arg.Key, post_arg.Value);
}
WWW www = new WWW(url, form);

StartCoroutine(WaitForRequest(www, Callback));
return www;
}



///
/// Waits for request.
///

/// The WWW.
/// The callback.
/// This is texture or not.
/// System.Collections.IEnumerator.
private IEnumerator WaitForRequest(WWW www, System.Action Callback = null, bool isTexture = false)
{
yield return www;
Object r;
if (www.error == null)
{
//Ok
if (!isTexture)
r = "{err:false,data:" + www.text + "}";
else
r = www.texture;

if (Callback != null)
Callback(r);
}
else
{
//send error
r = "{err:\"" + www.error + "\",data:false}";
if (Callback != null)
Callback(r);
}
}

///
/// Generic Asset Downloader ( Non Cached Version)
///

/// System.Object as Parameter to callback
private IEnumerator WaitForAsset(string BundleURL, string AssetName, System.Action Callback = null, bool isTexture = false)
{
// string BundleURL = "localhost:3000/prefabs/t1.unity3d";
// string AssetName = "t1";


using (WWW www = new WWW(BundleURL))
{
yield return www;
AssetBundle bundle;


if (www.error == null)
{
//Ok
bundle = www.assetBundle;

if (Callback != null)
{
if (AssetName == "")
Callback(bundle.mainAsset);
else
Callback(bundle.Load(AssetName));
}
bundle.Unload(false);
}
else
{
//send error
Object r = "{err:\"" + www.error + "\",data:false}";
if (Callback != null)
Callback(r);
}


} // memory is freed from the web stream (www.Dispose() gets called implicitly)
}

}

Example USAGE CODE

For example, create a file and fill it up with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

using System;
using System.Collections;
using System.Collections.Generic;
using SimpleJSON;
using Object = System.Object;
using D3VRestWrapper;

public class main : MonoBehaviour
{
D3VRest db;
Texture2D boxTex;
GameObject box;
// Use this for initialization
void Start()
{
db = GameObject.Find("DB").GetComponent();
FetchJackpot();


FetchTexure();



}

///
/// Fetches the texure.
///

public void FetchTexure()
{
db.GETTexture("http://localhost:3000/textures/playBtn.png", delegate(object data) {
boxTex=data as Texture2D;
GameObject.Find("Quad").renderer.material.mainTexture=boxTex;

FetchT();
});
}

///
/// Fetches the jackpot.
///

public void FetchJackpot()
{
db.GET("http://localhost:3000/jackpot", delegate(Object data)
{
//Data has been Received. Lets convert the returned object to JSON data
var www = JSON.Parse(data.ToString());

//CHeck if Error is present or not. ( and hopefully not!)
if (!www["err"].AsBool)
{
//Check if data is present or not
if (www["data"] != null && www["data"]["score"] != null)
{
print("Score: " + www["data"]["score"].Value);
GameObject.Find("lblJackpot").GetComponent().text = "Jackpot: " + www["data"]["score"].Value;
}
else
Debug.LogWarning("Score: 0");
}
else
{
Debug.LogError("Error Occured! : " + www["err"].ToString());
}
});
}


///
/// Updates the jackpot.
///

public void UpdateJackpot()
{
//Prepare Data to be Sent
Dictionary<string, string> form = new Dictionary<string, string>();
form.Add("score", GameObject.Find("inpJackpot").GetComponent().value);


//Send the data
db.POST("http://localhost:3000/jackpot", form, delegate(Object data)
{
var www = JSON.Parse(data.ToString());
if (!www["err"].AsBool)
{
FetchJackpot();
Debug.Log("Score Updated!");
}
else
{
Debug.LogError("Error Occured! : " + www["err"].ToString());
}
});
}


public void FetchT()
{
db.GETAsset("localhost:3000/prefabs/t1.unity3d", "t1", delegate(Object data) {
box = Instantiate((UnityEngine.Object)data) as GameObject;
box.renderer.material.mainTexture = boxTex;
});
}



}

Genrally, this simple REST utility for unity could be enhanced more and JSON can be integrated as well. I will leave this upto you. Or may be I will find out time to add more features to it and add it to my very own Utility Library ( _unity).