-
Notifications
You must be signed in to change notification settings - Fork 14
/
URLClientDemo.cs
474 lines (384 loc) · 11.5 KB
/
URLClientDemo.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
using UnityEngine;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Collections;
// add the following to avoid having to prepend everything with "URLClient."
using URLClient;
public class URLClientDemo : MonoBehaviour
{
HTTPClient _client;
string _test = "";
string _log = "";
int _curIndex;
int _demoIndex;
delegate IEnumerator DemoFunction();
DemoFunction[] _demos;
float _initialTime;
void Awake()
{
_demos = new DemoFunction[]
{
DemoSimple,
DemoFormPost,
DemoFilePost,
DemoQueryHeaderAndCookies,
DemoAcceptableStatusCodes,
DemoHTTPS,
DemoAcceptInvalidHTTPSCertificates,
DemoBasicAuthClient,
DemoRedirectControl,
DemoTimeoutControl,
DemoCacheControl,
DemoErrorHandling,
DemoBigFileIntegrityTest,
DemoBigFileDownload
};
Next();
_demoIndex = 0;
}
IEnumerator DemoSimple()
{
_test = "DemoSimple";
using (_client = new HTTPClient("unity3d.com"))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoFormPost()
{
_test = "DemoFormPost";
HTTPRequest request = new HTTPRequest();
request.SetURL("http://www.hashemian.com/tools/form-post-tester.php/test123").
SetContentString("foo=bar&cafe=babe", "application/octet-stream").
Post();
using (_client = new HTTPClient(request))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoFilePost()
{
_test = "DemoFilePost";
string srcPath = Application.temporaryCachePath;
srcPath = System.IO.Path.Combine(srcPath, "data");
byte[] data = Encoding.UTF8.GetBytes("hello\nworld\n!!!");
using (FileStream stream = new FileStream(srcPath, FileMode.Create,
FileAccess.Write, FileShare.ReadWrite))
{
stream.Write(data, 0, data.Length);
}
HTTPRequest request = new HTTPRequest();
request.SetURL("http://www.hashemian.com/tools/form-post-tester.php/test123").
SetContentFromPath(srcPath, "application/octet-stream").
Post();
using (_client = new HTTPClient(request))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoQueryHeaderAndCookies()
{
_test = "DemoQueryHeaderAndCookies";
HTTPRequest request = new HTTPRequest();
request.SetURL("http://www.google.com").
AppendQueryParameter("q", "unity").
SetHeader("User-Agent", "dummy user agent").
AppendCookie("name", "value").
Get();
using (_client = new HTTPClient(request))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoAcceptableStatusCodes()
{
_test = "DemoAcceptableStatusCodes";
HTTPRequest request = new HTTPRequest();
request.SetURL("http://google.com/nonexistent").
AppendQueryParameter("q", "unity");
HTTPResponseMemoryStreamHandler responseHandler =
new HTTPResponseMemoryStreamHandler();
responseHandler.AddAcceptableStatusCodeRange(200, 299);
using (_client = new HTTPClient(request, responseHandler))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoHTTPS()
{
_test = "DemoHTTPS";
HTTPRequest request = new HTTPRequest();
request.SetURL("https://google.com").
AppendQueryParameter("q", "unity");
using (_client = new HTTPClient(request))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoAcceptInvalidHTTPSCertificates()
{
_test = "DemoAcceptInvalidHTTPSCertificates";
HTTPRequest request = new HTTPRequest();
request.SetURL("https://google.com").
AppendQueryParameter("q", "unity");
HTTPResponseMemoryStreamHandler responseHandler =
new HTTPResponseMemoryStreamHandler();
responseHandler.SetAllowInvalidSSLCertificates(true);
using (_client = new HTTPClient(request, responseHandler))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoBasicAuthClient()
{
_test = "DemoBasicAuthClient";
HTTPRequest request = new HTTPRequest();
request.SetURL("http://browserspy.dk/password-ok.php").
SetAuthCredential("test", "test");
using (_client = new HTTPClient(request))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoRedirectControl()
{
_test = "DemoRedirectControl";
HTTPRequest request = new HTTPRequest();
request.SetURL("https://google.com").
AppendQueryParameter("q", "unity");
HTTPResponseMemoryStreamHandler responseHandler =
new HTTPResponseMemoryStreamHandler();
responseHandler.SetAllowFollowRedirects(true);
responseHandler.SetMaxRedirectCount(10);
using (_client = new HTTPClient(request, responseHandler))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoTimeoutControl()
{
_test = "DemoTimeoutControl";
HTTPRequest request = new HTTPRequest();
request.SetURL("http://www.wikipedia.com");
using (_client = new HTTPClient(request))
{
_client.ConnectionTimeout = 0.01f;
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
Error err = _client.Error;
if (err != null)
{
_log += "\n\nIs Timeout Error? " +
(err.IsKnownCode(Error.KnownCode.ConnectionTimeoutError) ? "YES" : "NO");
}
}
}
IEnumerator DemoCacheControl()
{
_test = "DemoCacheControl";
HTTPRequest request = new HTTPRequest();
request.SetURL("http://www.google.com").
AppendQueryParameter("q", "unity");
HTTPResponseMemoryStreamHandler responseHandler =
new HTTPResponseMemoryStreamHandler();
responseHandler.SetCachePolicy(CachePolicy.ReloadIgnoringLocalAndRemoteCacheData);
using (_client = new HTTPClient(request, responseHandler))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
}
}
IEnumerator DemoErrorHandling()
{
_test = "DemoErrorHandling";
HTTPRequest request = new HTTPRequest();
request.SetURL("http://www.wikipeeeeeedia.com");
using (_client = new HTTPClient(request))
{
yield return StartCoroutine(_client.WaitUntilDone());
DebugAll(_client);
Error err = _client.Error;
if (err != null)
{
_log += "\n\nIs Host Lookup Error? " +
(err.IsKnownCode(Error.KnownCode.HostLookupError) ? "YES" : "NO");
}
}
}
IEnumerator DemoBigFileIntegrityTest()
{
_test = "DemoBigFileIntegrityTest";
// By default, Unity-URLClient loads data into memory, and therefore
// loading a big file into memory like this, is NOT recommended!
// In order to reduce big data buffer exchange between native and unity side,
// and in order to have a constantly updated buffer in unity side, Unity-URLClient
// periodically buffers data from native into unity side. For that reason,
// we're testing here if the data is correctly assembled back into one
// piece by checking the MD5 of the downloaded data with the expected MD5.
//
// See DemoBigFileDownload() below for how to download directly into a file.
string url = "http://imgsrc.hubblesite.org/hu/db/images/hs-2012-01-a-print.jpg";
using (_client = new HTTPClient(url))
{
DebugClient(_client);
while (!_client.IsDone)
{
DebugClient(_client);
DebugTimeAndSpeed(_client);
yield return null;
}
DebugAll(_client);
string result;
Error err = _client.Error;
if ((err != null) || (_client.Response == null))
{
result = "ERROR: Integrity check aborted";
}
else
{
byte[] bytes = _client.Response.ContentToBytes();
if (bytes == null)
{
result = "ERROR: Integrity check aborted (NO DATA RECEIVED)";
}
else if (bytes.Length != 3107578)
{
result = "ERROR: Integrity check aborted (LENGTH MISMATCH)";
}
else
{
string received = MD5Hash(bytes);
string expected = "e6c6c2a83c5911df3aaec06408729201";
if (received != expected)
{
result = "ERROR: Integrity check failed (CHECKSUM EXPECTED: " +
expected + " BUT GOT " + received + ")";
}
else
{
result = "OK: Integrity check passed!";
}
}
}
_log = result + "\n\n" + _log;
}
}
string MD5Hash(byte[] bytes)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string hash = BitConverter.ToString(md5.ComputeHash(bytes));
return hash.Replace("-", "").ToLower();
}
IEnumerator DemoBigFileDownload()
{
_test = "DemoBigFileDownload";
string url = "http://netstorage.unity3d.com/unity/unity-4.1.5.dmg";
string destinationPath = Application.temporaryCachePath;
destinationPath = System.IO.Path.Combine(destinationPath, "unity-4.1.5.dmg");
using (_client = new HTTPClient(url, destinationPath))
{
DebugClient(_client);
while (!_client.IsDone)
{
DebugClient(_client);
DebugTimeAndSpeed(_client);
yield return null;
}
DebugAll(_client);
}
}
#region utility methods
void DebugAll(HTTPClient _client)
{
DebugClient(_client);
DebugResponseString(_client);
DebugTimeAndSpeed(_client);
}
void DebugClient(HTTPClient _client)
{
IHTTPResponse response = _client.Response;
_log = _client.ToString();
if (response == null)
{
_log += "\nAwaiting response...";
}
}
void DebugResponseString(HTTPClient _client)
{
if (_client.Response != null)
{
_log += "\n\nResponse Content\n";
string str = _client.Response.ContentToString();
if ((str != null) && (str.Length > 1024))
{
str = str.Substring(0, 1024) + "... (shortened)";
}
_log += str;
}
}
void DebugTimeAndSpeed(HTTPClient _client)
{
float duration = (Time.realtimeSinceStartup - _initialTime);
_log += "\nElapsed (secs): " + duration;
if ((duration > 0f) && (_client.Response != null))
{
float speed = (_client.Response.ReceivedContentLength / 1024f) / duration;
_log += "\nAvg Speed (KBytes/sec): " + speed;
}
}
void Next()
{
_demoIndex = (_demoIndex + 1) % _demos.Length;
}
IEnumerator StartDemo()
{
_initialTime = Time.realtimeSinceStartup;
_log = "";
_curIndex = _demoIndex;
yield return StartCoroutine(_demos[_demoIndex]());
if (_client != null)
{
_client.Dispose();
_client = null;
}
Next();
}
void OnGUI()
{
GUIStyle style;
style = new GUIStyle(GUI.skin.box);
style.wordWrap = true;
style.padding = new RectOffset(5, 5, 5, 5);
style.normal.textColor = Color.white;
GUI.skin.box = style;
Rect rect;
rect = new Rect(0, 0, Screen.width, Screen.height);
string text = String.Format("{0}/{1}: {2}\n\n{3}",
_curIndex + 1, _demos.Length, _test, _log);
GUI.Box(rect, text);
rect = new Rect(10, Screen.height - 100, Screen.width - 20, 90);
if (_client != null)
{
if (GUI.Button(rect, "CANCEL"))
{
_client.Cancel();
}
}
else if (GUI.Button(rect, "NEXT"))
{
StartCoroutine(StartDemo());
}
}
#endregion
}