RequestNode.cs
3.93 KB
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
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Globanet;
using Newtonsoft.Json;
namespace Globanet
{
namespace REST
{
public class RequestNode : MonoBehaviour
{
void Awake()
{
DontDestroyOnLoad(this);
}
private RequestData data = null;
private float delay = 0;
public void Initialize(RequestData data, float delay)
{
this.data = data;
this.delay = delay;
StartCoroutine(SendRequest());
}
private IEnumerator SendRequest()
{
yield return new WaitForSeconds(delay);
string url = data.url;
/*
//need to figure out the best way of handling this
if (data.endpoint != null)
{
string endpoint = data.endpoint;
//url = CmsSettings.url + "/" + endpoint;
}
else if (data.url != null)
{
url = data.url;
}*/
//if (endpoint[endpoint.Length - 1] != '/')
// endpoint += '/';
if (data.method != RequestMethod.GET && data.data == null)
{
var d = new Dictionary<string, string>();
d.Add("foo", "bar");
data.data = d;
}
Debug.Log("Request Data: " + JsonConvert.SerializeObject(data.data));
byte[] postData = null;
if (data.data != null)
postData = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data.data));
var headers = data.headers;
if (headers == null)
headers = new Dictionary<string, string>();
if (!headers.ContainsKey("Content-Type"))
headers.Add("Content-Type", "application/json");
if (!headers.ContainsKey("X-HTTP-Method-Override"))
headers.Add("X-HTTP-Method-Override", data.method.ToString());
if (!headers.ContainsKey("Authentication"))
{
if (!string.IsNullOrEmpty(data.authentication))
headers.Add("Authorization", data.authentication);
}
Debug.Log(data.method + " request to " + url);
WWW request = new WWW(url, postData, headers);
yield return request;
ResponseData response = new ResponseData();
response.request = data;
if (!string.IsNullOrEmpty(request.error))
{
print(request.error);
try
{
response.error = request.error;
response.errorCode = System.Convert.ToInt32(System.Text.RegularExpressions.Regex.Match(request.error, @"\d+").Value);
}
catch (System.FormatException)
{
if (request.error == "couldn't connect to host")
{
response.error = request.error;
response.errorCode = 7;
}
else
{
response.error = request.error;
response.errorCode = 99;
}
}
}
else
{
response.text = request.text;
//response.data = JsonConvert.DeserializeObject(request.text);
}
if (data.callback != null)
data.callback(response);
Destroy(gameObject);
}
}
}
}