/
Rest.cs
289 lines (257 loc) · 17 KB
/
Rest.cs
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// REST Class for CRUD Transactions.
/// </summary>
public static class Rest
{
#region Authentication
/// <summary>
/// Gets the Basic auth header.
/// </summary>
/// <param name="username">The Username.</param>
/// <param name="password">The password.</param>
/// <returns>The Basic authorization header encoded to base 64.</returns>
public static string GetBasicAuthentication(string username, string password)
{
return $"Basic {Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{password}"))}";
}
/// <summary>
/// Gets the Bearer auth header.
/// </summary>
/// <param name="authToken">OAuth Token to be used.</param>
/// <returns>The Bearer authorization header.</returns>
public static string GetBearerOAuthToken(string authToken)
{
return $"Bearer {authToken}";
}
#endregion Authentication
#region GET
/// <summary>
/// Rest GET.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="downloadHandler">Optional DownloadHandler for the request.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> GetAsync(string query, Dictionary<string, string> headers = null, int timeout = -1, DownloadHandler downloadHandler = null, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Get(query))
{
if (downloadHandler != null)
{
webRequest.downloadHandler = downloadHandler;
}
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
#endregion GET
#region POST
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(string query, Dictionary<string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Post(query, null as string))
{
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="formData">Form Data.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(string query, WWWForm formData, Dictionary<string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Post(query, formData))
{
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="jsonData">JSON data for the request.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(string query, string jsonData, Dictionary<string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Post(query, "POST"))
{
var data = new UTF8Encoding().GetBytes(jsonData);
webRequest.uploadHandler = new UploadHandlerRaw(data);
webRequest.downloadHandler = new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SetRequestHeader("Accept", "application/json");
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="bodyData">The raw data to post.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(string query, byte[] bodyData, Dictionary<string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Post(query, "POST"))
{
webRequest.uploadHandler = new UploadHandlerRaw(bodyData);
webRequest.downloadHandler = new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/octet-stream");
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
#endregion POST
#region PUT
/// <summary>
/// Rest PUT.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="jsonData">Data to be submitted.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PutAsync(string query, string jsonData, Dictionary<string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Put(query, jsonData))
{
webRequest.SetRequestHeader("Content-Type", "application/json");
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
/// <summary>
/// Rest PUT.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="bodyData">Data to be submitted.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PutAsync(string query, byte[] bodyData, Dictionary<string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Put(query, bodyData))
{
webRequest.SetRequestHeader("Content-Type", "application/octet-stream");
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
#endregion PUT
#region DELETE
/// <summary>
/// Rest DELETE.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="headers">Optional header information for the request.</param>
/// <param name="timeout">Optional time in seconds before request expires.</param>
/// <param name="readResponseData">Optional bool. If its true, response data will be read from web request download handler.</param>
/// <param name="certificateHandler">Optional certificate handler for custom certificate verification</param>
/// <param name="disposeCertificateHandlerOnDispose">Optional bool. If true and <paramref name="certificateHandler"/> is not null, <paramref name="certificateHandler"/> will be disposed, when the underlying UnityWebRequest is disposed.</param>
/// <returns>The response data.</returns>
public static async Task<Response> DeleteAsync(string query, Dictionary<string, string> headers = null, int timeout = -1, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
using (var webRequest = UnityWebRequest.Delete(query))
{
return await ProcessRequestAsync(webRequest, timeout, headers, readResponseData, certificateHandler, disposeCertificateHandlerOnDispose);
}
}
#endregion DELETE
private static async Task<Response> ProcessRequestAsync(UnityWebRequest webRequest, int timeout, Dictionary<string, string> headers = null, bool readResponseData = false, CertificateHandler certificateHandler = null, bool disposeCertificateHandlerOnDispose = true)
{
if (timeout > 0)
{
webRequest.timeout = timeout;
}
if (headers != null)
{
foreach (var header in headers)
{
webRequest.SetRequestHeader(header.Key, header.Value);
}
}
// HACK: Workaround for extra quotes around boundary.
if (webRequest.method == UnityWebRequest.kHttpVerbPOST ||
webRequest.method == UnityWebRequest.kHttpVerbPUT)
{
string contentType = webRequest.GetRequestHeader("Content-Type");
if (contentType != null)
{
contentType = contentType.Replace("\"", "");
webRequest.SetRequestHeader("Content-Type", contentType);
}
}
webRequest.certificateHandler = certificateHandler;
webRequest.disposeCertificateHandlerOnDispose = disposeCertificateHandlerOnDispose;
await webRequest.SendWebRequest();
long responseCode = webRequest.responseCode;
Func<byte[]> downloadHandlerDataAction = () => webRequest.downloadHandler?.data;
#if UNITY_2020_1_OR_NEWER
if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
#else
if (webRequest.isNetworkError || webRequest.isHttpError)
#endif // UNITY_2020_1_OR_NEWER
{
if (responseCode == 401) { return new Response(false, "Invalid Credentials", null, responseCode); }
if (webRequest.GetResponseHeaders() == null)
{
return new Response(false, "Device Unavailable", null, responseCode);
}
string responseHeaders = webRequest.GetResponseHeaders().Aggregate(string.Empty, (current, header) => $"\n{header.Key}: {header.Value}");
string downloadHandlerText = await ResponseUtils.BytesToString(downloadHandlerDataAction.Invoke());
Debug.LogError($"REST Error: {responseCode}\n{downloadHandlerText}{responseHeaders}");
return new Response(false, $"{responseHeaders}\n{downloadHandlerText}", downloadHandlerDataAction.Invoke(), responseCode);
}
if (readResponseData)
{
return new Response(true, await ResponseUtils.BytesToString(downloadHandlerDataAction.Invoke()), downloadHandlerDataAction.Invoke(), responseCode);
}
else // This option can be used only if action will be triggered in the same scope as the webrequest
{
return new Response(true, downloadHandlerDataAction, responseCode);
}
}
}
}