forked from andyburke/UnityHTTP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequest.cs
367 lines (317 loc) · 10.6 KB
/
Request.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
using UnityEngine;
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Globalization;
using System.Threading;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace HTTP
{
public class HTTPException : Exception
{
public HTTPException (string message) : base(message)
{
}
}
public enum RequestState {
Waiting, Reading, Done
}
public class Request
{
public static bool LogAllRequests = false;
public static bool VerboseLogging = false;
public CookieJar cookieJar = CookieJar.Instance;
public string method = "GET";
public string protocol = "HTTP/1.1";
public byte[] bytes;
public Uri uri;
public static byte[] EOL = { (byte)'\r', (byte)'\n' };
public Response response = null;
public bool isDone = false;
public int maximumRetryCount = 8;
public bool acceptGzip = true;
public bool useCache = false;
public Exception exception = null;
public RequestState state = RequestState.Waiting;
public long responseTime = 0; // in milliseconds
public bool synchronous = false;
public Action< HTTP.Request > completedCallback = null;
Dictionary<string, List<string>> headers = new Dictionary<string, List<string>> ();
static Dictionary<string, string> etags = new Dictionary<string, string> ();
public Request (string method, string uri)
{
this.method = method;
this.uri = new Uri (uri);
}
public Request (string method, string uri, bool useCache)
{
this.method = method;
this.uri = new Uri (uri);
this.useCache = useCache;
}
public Request (string method, string uri, byte[] bytes)
{
this.method = method;
this.uri = new Uri (uri);
this.bytes = bytes;
}
public Request( string method, string uri, WWWForm form )
{
this.method = method;
this.uri = new Uri (uri);
this.bytes = form.data;
foreach ( DictionaryEntry entry in form.headers )
{
this.AddHeader( (string)entry.Key, (string)entry.Value );
}
}
public Request( string method, string uri, Hashtable data )
{
this.method = method;
this.uri = new Uri( uri );
this.bytes = Encoding.UTF8.GetBytes( JSON.JsonEncode( data ) );
this.AddHeader( "Content-Type", "application/json" );
}
public void AddHeader (string name, string value)
{
name = name.ToLower ().Trim ();
value = value.Trim ();
if (!headers.ContainsKey (name))
headers[name] = new List<string> ();
headers[name].Add (value);
}
public string GetHeader (string name)
{
name = name.ToLower ().Trim ();
if (!headers.ContainsKey (name))
return "";
return headers[name][0];
}
public List< string > GetHeaders()
{
List< string > result = new List< string >();
foreach (string name in headers.Keys) {
foreach (string value in headers[name]) {
result.Add( name + ": " + value );
}
}
return result;
}
public List<string> GetHeaders (string name)
{
name = name.ToLower ().Trim ();
if (!headers.ContainsKey (name))
headers[name] = new List<string> ();
return headers[name];
}
public void SetHeader (string name, string value)
{
name = name.ToLower ().Trim ();
value = value.Trim ();
if (!headers.ContainsKey (name))
headers[name] = new List<string> ();
headers[name].Clear ();
headers[name].TrimExcess();
headers[name].Add (value);
}
// TODO: get rid of this when Unity's default monodevelop supports default arguments
public void Send()
{
Send( null );
}
private void GetResponse() {
System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch();
curcall.Start();
try {
var retry = 0;
while (++retry < maximumRetryCount) {
if (useCache) {
string etag = "";
if (etags.TryGetValue (uri.AbsoluteUri, out etag)) {
SetHeader ("If-None-Match", etag);
}
}
SetHeader ("Host", uri.Host);
var client = new TcpClient ();
client.Connect (uri.Host, uri.Port);
using (var stream = client.GetStream ()) {
var ostream = stream as Stream;
if (uri.Scheme.ToLower() == "https") {
ostream = new SslStream (stream, false, new RemoteCertificateValidationCallback (ValidateServerCertificate));
try {
var ssl = ostream as SslStream;
ssl.AuthenticateAsClient (uri.Host);
} catch (Exception e) {
Debug.LogError ("Exception: " + e.Message);
return;
}
}
WriteToStream (ostream);
response = new Response ();
response.request = this;
state = RequestState.Reading;
response.ReadFromStream(ostream);
}
client.Close ();
switch (response.status) {
case 307:
case 302:
case 301:
uri = new Uri (response.GetHeader ("Location"));
continue;
default:
retry = maximumRetryCount;
break;
}
}
if (useCache) {
string etag = response.GetHeader ("etag");
if (etag.Length > 0)
etags[uri.AbsoluteUri] = etag;
}
} catch (Exception e) {
Console.WriteLine ("Unhandled Exception, aborting request.");
Console.WriteLine (e);
exception = e;
response = null;
}
state = RequestState.Done;
isDone = true;
responseTime = curcall.ElapsedMilliseconds;
if ( completedCallback != null )
{
if (synchronous) {
completedCallback(this);
} else {
// we have to use this dispatcher to avoid executing the callback inside this worker thread
ResponseCallbackDispatcher.Singleton.requests.Enqueue( this );
}
}
if ( LogAllRequests )
{
#if !UNITY_EDITOR
System.Console.WriteLine("NET: " + InfoString( VerboseLogging ));
#else
if ( response != null && response.status >= 200 && response.status < 300 )
{
Debug.Log( InfoString( VerboseLogging ) );
}
else if ( response != null && response.status >= 400 )
{
Debug.LogError( InfoString( VerboseLogging ) );
}
else
{
Debug.LogWarning( InfoString( VerboseLogging ) );
}
#endif
}
}
public void Send( Action< HTTP.Request > callback )
{
if (!synchronous && callback != null && ResponseCallbackDispatcher.Singleton == null )
{
ResponseCallbackDispatcher.Init();
}
completedCallback = callback;
isDone = false;
state = RequestState.Waiting;
if (acceptGzip)
SetHeader ("Accept-Encoding", "gzip");
if ( this.cookieJar != null )
{
List< Cookie > cookies = this.cookieJar.GetCookies( new CookieAccessInfo( uri.Host, uri.AbsolutePath ) );
string cookieString = this.GetHeader( "cookie" );
for ( int cookieIndex = 0; cookieIndex < cookies.Count; ++cookieIndex )
{
if ( cookieString.Length > 0 && cookieString[ cookieString.Length - 1 ] != ';' )
{
cookieString += ';';
}
cookieString += cookies[ cookieIndex ].name + '=' + cookies[ cookieIndex ].value + ';';
}
SetHeader( "cookie", cookieString );
}
if ( bytes != null && bytes.Length > 0 && GetHeader ("Content-Length") == "" ) {
SetHeader( "Content-Length", bytes.Length.ToString() );
}
if ( GetHeader( "User-Agent" ) == "" ) {
SetHeader( "User-Agent", "UnityWeb 1.0 ( Unity " + Application.unityVersion + " ) ( " + SystemInfo.operatingSystem + " )" );
}
if ( GetHeader( "Connection" ) == "" ) {
SetHeader( "Connection", "close" );
}
// Basic Authorization
if (!String.IsNullOrEmpty(uri.UserInfo)) {
SetHeader("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(uri.UserInfo)));
}
if (synchronous) {
GetResponse();
} else {
ThreadPool.QueueUserWorkItem (new WaitCallback ( delegate(object t) {
GetResponse();
}));
}
}
public string Text {
set { bytes = System.Text.Encoding.UTF8.GetBytes (value); }
}
public static bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
#if !UNITY_EDITOR
System.Console.WriteLine( "NET: SSL Cert: " + sslPolicyErrors.ToString() );
#else
Debug.LogWarning("SSL Cert Error: " + sslPolicyErrors.ToString ());
#endif
return true;
}
void WriteToStream (Stream outputStream)
{
var stream = new BinaryWriter (outputStream);
stream.Write (ASCIIEncoding.ASCII.GetBytes (method.ToUpper () + " " + uri.PathAndQuery + " " + protocol));
stream.Write (EOL);
foreach (string name in headers.Keys) {
foreach (string value in headers[name]) {
stream.Write (ASCIIEncoding.ASCII.GetBytes (name));
stream.Write (':');
stream.Write (ASCIIEncoding.ASCII.GetBytes (value));
stream.Write (EOL);
}
}
stream.Write (EOL);
if (bytes != null && bytes.Length > 0) {
stream.Write (bytes);
}
}
private static string[] sizes = { "B", "KB", "MB", "GB" };
public string InfoString( bool verbose )
{
string status = isDone && response != null ? response.status.ToString() : "---";
string message = isDone && response != null ? response.message : "Unknown";
double size = isDone && response != null && response.bytes != null ? response.bytes.Length : 0.0f;
int order = 0;
while ( size >= 1024.0f && order + 1 < sizes.Length )
{
++order;
size /= 1024.0f;
}
string sizeString = String.Format( "{0:0.##}{1}", size, sizes[ order ] );
string result = uri.ToString() + " [ " + method.ToUpper() + " ] [ " + status + " " + message + " ] [ " + sizeString + " ] [ " + responseTime + "ms ]";
if ( verbose && response != null )
{
result += "\n\nRequest Headers:\n\n" + String.Join( "\n", GetHeaders().ToArray() );
result += "\n\nResponse Headers:\n\n" + String.Join( "\n", response.GetHeaders().ToArray() );
if ( response.Text != null )
{
result += "\n\nResponse Body:\n" + response.Text;
}
}
return result;
}
}
}