From b42ac17b40f9c2d3ed82883078c9942d626f96af Mon Sep 17 00:00:00 2001 From: paynechu <314176+paynechu@users.noreply.github.com> Date: Tue, 4 Jun 2013 09:53:55 +0800 Subject: [PATCH 1/2] - adjusted the User-Agent to fit standard format --- Request.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.cs b/Request.cs index 3d13b7c..1b5afdd 100644 --- a/Request.cs +++ b/Request.cs @@ -274,7 +274,7 @@ public void Send( Action< HTTP.Request > callback ) } if ( GetHeader( "User-Agent" ) == "" ) { - SetHeader( "User-Agent", "UnityWeb 1.0 ( Unity " + Application.unityVersion + " ) ( " + SystemInfo.operatingSystem + " )" ); + SetHeader("User-Agent", "UnityWeb/1.0 (Unity " + Application.unityVersion + "; " + SystemInfo.operatingSystem + ")"); } if ( GetHeader( "Connection" ) == "" ) { From a87379cd459569b73f759118013049912695cf3e Mon Sep 17 00:00:00 2001 From: paynechu <314176+paynechu@users.noreply.github.com> Date: Wed, 16 Dec 2015 19:08:31 +0800 Subject: [PATCH 2/2] - fixed for Unity 5.2+ --- Request.cs | 236 +++++++++++++++++++++++------------------------ external/JSON.cs | 3 +- 2 files changed, 118 insertions(+), 121 deletions(-) diff --git a/Request.cs b/Request.cs index 1b5afdd..9e473c5 100644 --- a/Request.cs +++ b/Request.cs @@ -15,19 +15,22 @@ namespace HTTP { public class HTTPException : Exception { - public HTTPException (string message) : base(message) + public HTTPException (string message) : base (message) { } } - public enum RequestState { - Waiting, Reading, Done + public enum RequestState + { + Waiting, + Reading, + Done } public class Request { - public static bool LogAllRequests = false; - public static bool VerboseLogging = false; + public static bool LogAllRequests = false; + public static bool VerboseLogging = false; public CookieJar cookieJar = CookieJar.Instance; public string method = "GET"; @@ -42,7 +45,8 @@ public class Request public bool useCache = false; public Exception exception = null; public RequestState state = RequestState.Waiting; - public long responseTime = 0; // in milliseconds + public long responseTime = 0; + // in milliseconds public bool synchronous = false; public Action< HTTP.Request > completedCallback = null; @@ -70,32 +74,31 @@ public Request (string method, string uri, byte[] bytes) this.bytes = bytes; } - public Request( string method, string uri, WWWForm form ) - { + 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" ); - } - + foreach (var 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 (); - headers[name].Add (value); + headers [name] = new List (); + headers [name].Add (value); } public string GetHeader (string name) @@ -103,27 +106,27 @@ public string GetHeader (string name) name = name.ToLower ().Trim (); if (!headers.ContainsKey (name)) return ""; - return headers[name][0]; + return headers [name] [0]; } - public List< string > GetHeaders() - { - List< string > result = new List< string >(); - foreach (string name in headers.Keys) { + 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 ); + result.Add (name + ": " + value); } } - return result; - } + return result; + } public List GetHeaders (string name) { name = name.ToLower ().Trim (); if (!headers.ContainsKey (name)) - headers[name] = new List (); - return headers[name]; + headers [name] = new List (); + return headers [name]; } public void SetHeader (string name, string value) @@ -131,21 +134,22 @@ public void SetHeader (string name, string value) name = name.ToLower ().Trim (); value = value.Trim (); if (!headers.ContainsKey (name)) - headers[name] = new List (); - headers[name].Clear (); - headers[name].TrimExcess(); - headers[name].Add (value); + headers [name] = new List (); + 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); } - // 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(); + private void GetResponse () + { + System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch (); + curcall.Start (); try { var retry = 0; @@ -163,7 +167,7 @@ private void GetResponse() { client.Connect (uri.Host, uri.Port); using (var stream = client.GetStream ()) { var ostream = stream as Stream; - if (uri.Scheme.ToLower() == "https") { + if (uri.Scheme.ToLower () == "https") { ostream = new SslStream (stream, false, new RemoteCertificateValidationCallback (ValidateServerCertificate)); try { var ssl = ostream as SslStream; @@ -177,7 +181,7 @@ private void GetResponse() { response = new Response (); response.request = this; state = RequestState.Reading; - response.ReadFromStream(ostream); + response.ReadFromStream (ostream); } client.Close (); @@ -195,7 +199,7 @@ private void GetResponse() { if (useCache) { string etag = response.GetHeader ("etag"); if (etag.Length > 0) - etags[uri.AbsoluteUri] = etag; + etags [uri.AbsoluteUri] = etag; } } catch (Exception e) { @@ -206,22 +210,20 @@ private void GetResponse() { } state = RequestState.Done; isDone = true; - responseTime = curcall.ElapsedMilliseconds; + responseTime = curcall.ElapsedMilliseconds; - if ( completedCallback != null ) - { + if (completedCallback != null) { if (synchronous) { - completedCallback(this); + completedCallback (this); } else { - // we have to use this dispatcher to avoid executing the callback inside this worker thread - ResponseCallbackDispatcher.Singleton.requests.Enqueue( this ); + // we have to use this dispatcher to avoid executing the callback inside this worker thread + ResponseCallbackDispatcher.Singleton.requests.Enqueue (this); } - } + } - if ( LogAllRequests ) - { + if (LogAllRequests) { #if !UNITY_EDITOR - System.Console.WriteLine("NET: " + InfoString( VerboseLogging )); + System.Console.WriteLine ("NET: " + InfoString (VerboseLogging)); #else if ( response != null && response.status >= 200 && response.status < 300 ) { @@ -236,61 +238,57 @@ private void GetResponse() { Debug.LogWarning( InfoString( VerboseLogging ) ); } #endif - } + } } - - public void Send( Action< HTTP.Request > callback ) + + public void Send (Action< HTTP.Request > callback) { - if (!synchronous && callback != null && ResponseCallbackDispatcher.Singleton == null ) - { - ResponseCallbackDispatcher.Init(); - } + if (!synchronous && callback != null && ResponseCallbackDispatcher.Singleton == null) { + ResponseCallbackDispatcher.Init (); + } - completedCallback = callback; + 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 ] != ';' ) - { + 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 + ';'; + cookieString += cookies [cookieIndex].name + '=' + cookies [cookieIndex].value + ';'; } - SetHeader( "cookie", cookieString ); - } + SetHeader ("cookie", cookieString); + } - if ( bytes != null && bytes.Length > 0 && GetHeader ("Content-Length") == "" ) { - SetHeader( "Content-Length", bytes.Length.ToString() ); - } + 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 ("User-Agent") == "") { + SetHeader ("User-Agent", "UnityWeb/1.0 (Unity " + Application.unityVersion + "; " + SystemInfo.operatingSystem + ")"); + } - if ( GetHeader( "Connection" ) == "" ) { - SetHeader( "Connection", "close" ); - } + 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 (!String.IsNullOrEmpty (uri.UserInfo)) { + SetHeader ("Authorization", "Basic " + System.Convert.ToBase64String (System.Text.ASCIIEncoding.ASCII.GetBytes (uri.UserInfo))); } if (synchronous) { - GetResponse(); + GetResponse (); } else { - ThreadPool.QueueUserWorkItem (new WaitCallback ( delegate(object t) { - GetResponse(); + ThreadPool.QueueUserWorkItem (new WaitCallback (delegate(object t) { + GetResponse (); })); } } @@ -303,7 +301,7 @@ public string Text { public static bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { #if !UNITY_EDITOR - System.Console.WriteLine( "NET: SSL Cert: " + sslPolicyErrors.ToString() ); + System.Console.WriteLine ("NET: SSL Cert: " + sslPolicyErrors.ToString ()); #else Debug.LogWarning("SSL Cert Error: " + sslPolicyErrors.ToString ()); #endif @@ -325,43 +323,41 @@ void WriteToStream (Stream outputStream) } } - 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; + private static string[] sizes = { "B", "KB", "MB", "GB" }; - int order = 0; - while ( size >= 1024.0f && order + 1 < sizes.Length ) - { - ++order; - size /= 1024.0f; - } + 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 sizeString = String.Format ("{0:0.##}{1}", size, sizes [order]); - string result = uri.ToString() + " [ " + method.ToUpper() + " ] [ " + status + " " + message + " ] [ " + sizeString + " ] [ " + responseTime + "ms ]"; + 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 (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; - } - } + if (response.Text != null) { + result += "\n\nResponse Body:\n" + response.Text; + } + } - return result; - } + return result; + } } } diff --git a/external/JSON.cs b/external/JSON.cs index 5c3fb00..2cd5ca9 100644 --- a/external/JSON.cs +++ b/external/JSON.cs @@ -35,7 +35,8 @@ public class JSON /// /// A JSON byte array. /// An ArrayList, a Hashtable, a double, a string, null, true, or false - public static object JsonDecode (byte[] json) { + public static object JsonDecode (byte[] json) + { return JsonDecode(System.Text.ASCIIEncoding.ASCII.GetString(json)); }