ReadFromStream() public method

public ReadFromStream ( Stream inputStream ) : void
inputStream Stream
return void
Esempio n. 1
0
        public void Send(string filePath = null, bool onlyContentLength = false)
        {
            isDone = false;
            state  = RequestState.Waiting;
            if (acceptGzip)
            {
                SetHeader("Accept-Encoding", "gzip");
            }
            //ThreadPool.QueueUserWorkItem (new WaitCallback (delegate(object t) {
            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);

                                                #if UNITY_WEBPLAYER
                    /*
                     * string ip = Dns.GetHostAddresses(uri.Host)[0].ToString();
                     * if (!Security.PrefetchSocketPolicy (ip, 1843)) {
                     *      Debug.LogError("Security Exception. Policy file load failed!");
                     * }*/
                                                #endif

                    var client = new TcpClient();


                    client.SendTimeout    = 5000;
                    client.ReceiveTimeout = 5000;

                    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);
                        if (filePath != null)
                        {
                            response = new Response(filePath, onlyContentLength);
                        }
                        else
                        {
                            response = new Response();
                        }

                        if (downloadDelegate != null)
                        {
                            response.downloadDelegate = downloadDelegate;
                        }

                        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 (SocketException e) {
                response.status = -100;
                if (downloadDelegate != null)
                {
                    IOErrorEvent ioErrorEvent = new IOErrorEvent();
                    ioErrorEvent.ErrorCode = e.ErrorCode;
                    ioErrorEvent.Message   = e.Message;
                    downloadDelegate.OnIOError(ioErrorEvent);
                }
                Debug.LogException(e);
            } catch (IOException ioex) {
                response.status = -100;
                if (downloadDelegate != null)
                {
                    IOErrorEvent ioErrorEvent = new IOErrorEvent();
                    ioErrorEvent.Message = ioex.Message;
                    downloadDelegate.OnIOError(ioErrorEvent);
                }

                Debug.LogException(ioex);
            } catch (Exception e) {
                Console.WriteLine("Unhandled Exception, aborting request.");
                Console.WriteLine(e);
                Debug.Log(e.Message + " Type: " + e.GetType().FullName);
                exception = e;
                response  = null;
            }

            //Debug.Log ("Request finished");
            state  = RequestState.Done;
            isDone = true;
            //}));
        }
Esempio n. 2
0
        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) {
#if !UNITY_EDITOR
                                Console.WriteLine("SSL authentication failed.");
                                Console.WriteLine(e);
#else
                                Debug.LogError("SSL authentication failed.");
                                Debug.LogException(e);
#endif
                                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) {
#if !UNITY_EDITOR
                Console.WriteLine("Unhandled Exception, aborting request.");
                Console.WriteLine(e);
#else
                Debug.LogError("Unhandled Exception, aborting request.");
                Debug.LogException(e);
#endif
                exception = e;
                response  = null;
            }

            state        = RequestState.Done;
            isDone       = true;
            responseTime = curcall.ElapsedMilliseconds;

            if (byteStream != null)
            {
                byteStream.Close();
            }

            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
            }
        }
Esempio n. 3
0
        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
            }            
        }
Esempio n. 4
0
        void BeginSending()
        {
            isDone = false;

            if (timeout > 0)
            {
                UniWeb.Instance.StartCoroutine(Timeout());
            }

            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object t) {
                try {
                    var retryCount            = 0;
                    HttpConnection connection = null;

                    while (retryCount < maximumRedirects)
                    {
                        AddHeadersToRequest();
                        Uri pUri;
                        if (proxy != null)
                        {
                            pUri = proxy;
                        }
                        else
                        {
#if UNITY_WP8
                            pUri = uri;
#else
                            if (System.Net.WebRequest.DefaultWebProxy != null)
                            {
                                pUri = System.Net.WebRequest.DefaultWebProxy.GetProxy(uri);
                            }
                            else
                            {
                                pUri = uri;
                            }
#endif
                        }

                        connection = CreateConnection(pUri.Host, pUri.Port, pUri.Scheme.ToLower() == "https");

                        WriteToStream(connection.stream);


                        response = new Response(this);
                        try {
                            response.ReadFromStream(connection.stream);
                        } catch (HTTPException) {
                            retryCount++;
                            continue;
                        }
#if USE_KEEPALIVE
                        connectionPool[pUri.Host] = connection;
#endif

#if USE_COOKIES
                        if (enableCookies)
                        {
                            foreach (var i in response.headers.GetAll("Set-Cookie"))
                            {
                                try {
                                    cookies.SetCookies(uri, i);
                                } catch (System.Net.CookieException) {
                                    //Some cookies make the .NET cookie class barf. MEGH.
                                }
                            }
                        }
#endif

                        switch (response.status)
                        {
                        case 101:
                            upgradedConnection = connection;
                            break;

                        case 304:
                            break;

                        case 307:
                            uri = new Uri(response.headers.Get("Location"));
                            retryCount++;
                            continue;

                        case 302:
                        case 301:
                            method       = "GET";
                            var location = response.headers.Get("Location");
                            if (location.StartsWith("/"))
                            {
                                uri = new Uri(uri, location);
                            }
                            else
                            {
                                uri = new Uri(location);
                            }

                            retryCount++;
                            continue;

                        default:
                            break;
                        }
                        break;
                    }

                    if (upgradedConnection == null)
                    {
#if USE_KEEPALIVE
                        if (response.protocol.ToUpper() == "HTTP/1.0" || response.headers.Get("Connection").ToUpper() == "CLOSE")
                        {
                            if (connectionPool.ContainsKey(uri.Host))
                            {
                                connectionPool.Remove(uri.Host);
                            }
                            connection.Dispose();
                        }
#else
                        connection.Dispose();
#endif
                    }

                    if (useCache && response != null)
                    {
                        var etag = response.headers.Get("etag");
                        if (etag.Length > 0)
                        {
                            etags [uri.AbsoluteUri] = etag;
                        }
                    }
                } catch (Exception e) {
                    exception = e;
                    response  = null;
                }
                isDone = true;
            }));
        }
Esempio n. 5
0
		public void Send ()
		{
			
			if (sent) {
				throw new InvalidOperationException ("Request has already completed.");	
			}
			sent = true;
			isDone = false;
			state = RequestState.Waiting;
#if USE_GZIP			
			if (acceptGzip) {
				headers.Set ("Accept-Encoding", "gzip");
			}
#endif
			if (timeout > 0)
				SimpleWWW.Instance.StartCoroutine (Timeout ());
			ThreadPool.QueueUserWorkItem (new WaitCallback (delegate(object t) {
				try {
					var retry = 0;
					while (++retry < maximumRedirects) {
						if (useCache) {
							string etag = "";
							if (etags.TryGetValue (uri.AbsoluteUri, out etag)) {
								headers.Set ("If-None-Match", etag);
							}
						}
						var hostHeader = uri.Host;
						if (uri.Port != 80 && uri.Port != 443) {
							hostHeader += ":" + uri.Port.ToString ();
						}
						headers.Set ("Host", hostHeader);
#if USE_COOKIES
						if (enableCookies && uri != null) {
							try {
								var c = cookies.GetCookieHeader (uri);
								if (c != null && c.Length > 0) {
									headers.Set ("Cookie", c);
								}
							} catch (NullReferenceException) {
								//Some cookies make the .NET cookie class barf. MEGH again.
							} catch (IndexOutOfRangeException) {
								//Another weird exception that comes through from the cookie class.	
							}
						}
#endif
						ActiveConnection connection = null;
						while (true) {
							
							try {
								//pull a connection from the pool (a new one is created if needed)
								connection = GetClient (uri.Host, uri.Port, uri.Scheme.ToLower () == "https");
							} catch (Exception e) {
								Debug.Log (e);
								exception = e;
								response = null;
								break;
							}
							try {
								WriteToStream (connection.stream);
							} catch (IOException e) {
								Debug.Log (e);
								exception = new IOException ("Server closed the connection:" + e.ToString ());
								response = null;
								break;
							}
							response = new Response (this);
							state = RequestState.Reading;
							try {
								response.ReadFromStream (connection.stream);
							} catch (IOException e) {
								Debug.Log (e);
								exception = new IOException ("Server closed the connection:" + e.ToString ());
								response = null;
								break;
							} catch (HTTPException) {
								continue;
							}
							break;
						}
						if (response != null) {
#if USE_COOKIES
							if (enableCookies) {
								foreach (var i in response.headers.GetAll("Set-Cookie")) {
									try {
										cookies.SetCookies (uri, i);
									} catch (System.Net.CookieException) {
										//Some cookies make the .NET cookie class barf. MEGH.
									}
								}
							}
#endif
							switch (response.status) {
							case 101:
								upgradedConnection = connection;
								retry = maximumRedirects;
								break;
							case 304:
								retry = maximumRedirects;
								break;
							case 307:
							case 302:
							case 301:
								uri = new Uri (response.headers.Get ("Location"));
								if (OnRedirect != null) {
									OnRedirect (uri);
									retry = maximumRedirects;
								}
								break;
							default:
								retry = maximumRedirects;
								break;
							}
							//close the connection back if not upgraded.
							if (upgradedConnection == null) {	
								lock (connectionPool) {
									var close = response.headers.Get ("Connection").ToLower () == "close";
									if (!close) {
										connectionPool.Add (connection);	
									} else {
										connection.stream.Close ();
									}
								}
							}
						}
					}
					if (useCache && response != null) {
						string etag = response.headers.Get ("etag");
						if (etag.Length > 0) {
							etags [uri.AbsoluteUri] = etag;
							SaveEtags ();
						}
					}
				} catch (Exception e) {
					Debug.Log (e);
					exception = e;
					response = null;
				}
				state = RequestState.Done;
				isDone = true;
			}));
		}
Esempio n. 6
0
        public void Send()
        {
            if (sent)
            {
                throw new InvalidOperationException("Request has already completed.");
            }
            sent   = true;
            isDone = false;
            state  = RequestState.Waiting;
#if USE_GZIP
            if (acceptGzip)
            {
                headers.Set("Accept-Encoding", "gzip");
            }
#endif
            if (timeout > 0)
            {
                SimpleWWW.Instance.StartCoroutine(Timeout());
            }
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object t) {
                try {
                    var retry = 0;
                    while (++retry < maximumRedirects)
                    {
                        if (useCache)
                        {
                            string etag = "";
                            if (etags.TryGetValue(uri.AbsoluteUri, out etag))
                            {
                                headers.Set("If-None-Match", etag);
                            }
                        }
                        var hostHeader = uri.Host;
                        if (uri.Port != 80 && uri.Port != 443)
                        {
                            hostHeader += ":" + uri.Port.ToString();
                        }
                        headers.Set("Host", hostHeader);
#if USE_COOKIES
                        if (enableCookies && uri != null)
                        {
                            try {
                                var c = cookies.GetCookieHeader(uri);
                                if (c != null && c.Length > 0)
                                {
                                    headers.Set("Cookie", c);
                                }
                            } catch (NullReferenceException) {
                                //Some cookies make the .NET cookie class barf. MEGH again.
                            } catch (IndexOutOfRangeException) {
                                //Another weird exception that comes through from the cookie class.
                            }
                        }
#endif
                        ActiveConnection connection = null;
                        while (true)
                        {
                            try {
                                //pull a connection from the pool (a new one is created if needed)
                                connection = GetClient(uri.Host, uri.Port, uri.Scheme.ToLower() == "https");
                            } catch (Exception e) {
                                Debug.Log(e);
                                exception = e;
                                response  = null;
                                break;
                            }
                            try {
                                WriteToStream(connection.stream);
                            } catch (IOException e) {
                                Debug.Log(e);
                                exception = new IOException("Server closed the connection:" + e.ToString());
                                response  = null;
                                break;
                            }
                            response = new Response(this);
                            state    = RequestState.Reading;
                            try {
                                response.ReadFromStream(connection.stream);
                            } catch (IOException e) {
                                Debug.Log(e);
                                exception = new IOException("Server closed the connection:" + e.ToString());
                                response  = null;
                                break;
                            } catch (HTTPException) {
                                continue;
                            }
                            break;
                        }
                        if (response != null)
                        {
#if USE_COOKIES
                            if (enableCookies)
                            {
                                foreach (var i in response.headers.GetAll("Set-Cookie"))
                                {
                                    try {
                                        cookies.SetCookies(uri, i);
                                    } catch (System.Net.CookieException) {
                                        //Some cookies make the .NET cookie class barf. MEGH.
                                    }
                                }
                            }
#endif
                            switch (response.status)
                            {
                            case 101:
                                upgradedConnection = connection;
                                retry = maximumRedirects;
                                break;

                            case 304:
                                retry = maximumRedirects;
                                break;

                            case 307:
                            case 302:
                            case 301:
                                uri = new Uri(response.headers.Get("Location"));
                                if (OnRedirect != null)
                                {
                                    OnRedirect(uri);
                                    retry = maximumRedirects;
                                }
                                break;

                            default:
                                retry = maximumRedirects;
                                break;
                            }
                            //close the connection back if not upgraded.
                            if (upgradedConnection == null)
                            {
                                lock (connectionPool) {
                                    var close = response.headers.Get("Connection").ToLower() == "close";
                                    if (!close)
                                    {
                                        connectionPool.Add(connection);
                                    }
                                    else
                                    {
                                        connection.stream.Close();
                                    }
                                }
                            }
                        }
                    }
                    if (useCache && response != null)
                    {
                        string etag = response.headers.Get("etag");
                        if (etag.Length > 0)
                        {
                            etags [uri.AbsoluteUri] = etag;
                            SaveEtags();
                        }
                    }
                } catch (Exception e) {
                    Debug.Log(e);
                    exception = e;
                    response  = null;
                }
                state  = RequestState.Done;
                isDone = true;
            }));
        }
Esempio n. 7
0
        private void GetResponse()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            try
            {
                int num = 0;
                while (++num < maximumRetryCount)
                {
                    if (useCache)
                    {
                        string value = "";
                        if (etags.TryGetValue(uri.AbsoluteUri, out value))
                        {
                            SetHeader("If-None-Match", value);
                        }
                    }
                    SetHeader("Host", uri.Host);
                    TcpClient tcpClient = new TcpClient();
                    tcpClient.Connect(uri.Host, uri.Port);
                    using (NetworkStream networkStream = tcpClient.GetStream())
                    {
                        Stream stream = networkStream;
                        if (uri.Scheme.ToLower() == "https")
                        {
                            stream = new SslStream(networkStream, leaveStreamOpen: false, ValidateServerCertificate);
                            try
                            {
                                SslStream sslStream = stream as SslStream;
                                sslStream.AuthenticateAsClient(uri.Host);
                            }
                            catch (Exception ex)
                            {
                                UnityEngine.Debug.LogError("Exception: " + ex.Message);
                                return;
                            }
                        }
                        WriteToStream(stream);
                        response         = new Response();
                        response.request = this;
                        state            = RequestState.Reading;
                        response.ReadFromStream(stream);
                    }
                    tcpClient.Close();
                    switch (response.status)
                    {
                    case 301:
                    case 302:
                    case 307:
                        uri = new Uri(response.GetHeader("Location"));
                        break;

                    default:
                        num = maximumRetryCount;
                        break;
                    }
                }
                if (useCache)
                {
                    string value = response.GetHeader("etag");
                    if (value.Length > 0)
                    {
                        etags[uri.AbsoluteUri] = value;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled Exception, aborting request.");
                Console.WriteLine(ex);
                exception = ex;
                response  = null;
            }
            state        = RequestState.Done;
            isDone       = true;
            responseTime = stopwatch.ElapsedMilliseconds;
            if (completedCallback != null)
            {
                if (synchronous)
                {
                    completedCallback(this);
                }
                else
                {
                    ResponseCallbackDispatcher.Singleton.requests.Enqueue(this);
                }
            }
            if (LogAllRequests)
            {
                Console.WriteLine("NET: " + InfoString(VerboseLogging));
            }
        }
Esempio n. 8
0
        public void Send()
        {
            isDone = false;
            state = RequestState.Waiting;

            if (acceptGzip)
                SetHeader ("Accept-Encoding", "gzip");
            ThreadPool.QueueUserWorkItem (new WaitCallback (delegate(object t) {
                try {

                    var retry = 0;
                    while (++retry < maximumRedirects) {
                        if (useCache) {
                            string etag = "";
                            if (etags.TryGetValue (uri.AbsoluteUri, out etag)) {
                                SetHeader ("If-None-Match", etag);
                            }
                        }
                        var hostHeader = uri.Host;
                        if (uri.Port != 80 && uri.Port != 443)
                            hostHeader += ":" + uri.Port.ToString ();
                        SetHeader ("Host", hostHeader);

                        ActiveConnection connection;
                        try {
                            //pull a connection from the pool (a new one is created if needed)
                            connection = GetClient (uri.Host, uri.Port, uri.Scheme.ToLower () == "https");
                        } catch (Exception e) {
                            exception = e;
                            response = null;
                            break;
                        }

                        try {
                            WriteToStream (connection.stream);
                        } catch (IOException e) {
                            exception = new IOException ("Server closed the connection:" + e.ToString ());
                            response = null;
                            break;
                        }
                        response = new Response (this);
                        state = RequestState.Reading;
                        try {
                            response.ReadFromStream (connection.stream);
                        } catch (IOException e) {
                            exception = new IOException ("Server closed the connection:" + e.ToString ());
                            response = null;
                            break;
                        }

                        switch (response.status) {
                        case 101:
                            upgradedConnection = connection;
                            retry = maximumRedirects;
                            break;
                        case 304:
                            retry = maximumRedirects;
                            break;
                        case 307:
                        case 302:
                        case 301:
                            uri = new Uri (response.GetHeader ("Location"));
                            if (OnRedirect != null) {
                                OnRedirect (uri);
                                retry = maximumRedirects;
                            }
                            break;
                        default:
                            retry = maximumRedirects;
                            break;
                        }
                        //place the connection back into the pool if not upgraded.
                        if(upgradedConnection == null) {
                            if (response.GetHeader ("Connection").ToLower () != "keep-alive") {
                                connection.stream.Close ();
                            }
                            activeConnections [connection.key].Add (connection);
                        }
                    }
                    if (useCache) {
                        string etag = response.GetHeader ("etag");
                        if (etag.Length > 0) {
                            etags [uri.AbsoluteUri] = etag;
                            SaveEtags ();
                        }
                    }
                } catch (Exception e) {
                    exception = e;
                    response = null;
                }
                state = RequestState.Done;
                isDone = true;
            }));
        }
Esempio n. 9
0
		public void Send ()
		{
			isDone = false;
			state = RequestState.Waiting;
			if (acceptGzip)
				SetHeader ("Accept-Encoding", "gzip");
			ThreadPool.QueueUserWorkItem (new WaitCallback (delegate(object t) {
				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 ();
							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;
			}));
		}
Esempio n. 10
0
        public void Send()
        {
            isDone = false;
            state  = RequestState.Waiting;

            if (acceptGzip)
            {
                SetHeader("Accept-Encoding", "gzip");
            }
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object t) {
                try {
                    var retry = 0;
                    while (++retry < maximumRedirects)
                    {
                        if (useCache)
                        {
                            string etag = "";
                            if (etags.TryGetValue(uri.AbsoluteUri, out etag))
                            {
                                SetHeader("If-None-Match", etag);
                            }
                        }
                        var hostHeader = uri.Host;
                        if (uri.Port != 80 && uri.Port != 443)
                        {
                            hostHeader += ":" + uri.Port.ToString();
                        }
                        SetHeader("Host", hostHeader);

                        ActiveConnection connection;
                        try {
                            //pull a connection from the pool (a new one is created if needed)
                            connection = GetClient(uri.Host, uri.Port, uri.Scheme.ToLower() == "https");
                        } catch (Exception e) {
                            exception = e;
                            response  = null;
                            break;
                        }

                        try {
                            WriteToStream(connection.stream);
                        } catch (IOException e) {
                            exception = new IOException("Server closed the connection:" + e.ToString());
                            response  = null;
                            break;
                        }
                        response = new Response(this);
                        state    = RequestState.Reading;
                        try {
                            response.ReadFromStream(connection.stream);
                        } catch (IOException e) {
                            exception = new IOException("Server closed the connection:" + e.ToString());
                            response  = null;
                            break;
                        }

                        switch (response.status)
                        {
                        case 101:
                            upgradedConnection = connection;
                            retry = maximumRedirects;
                            break;

                        case 304:
                            retry = maximumRedirects;
                            break;

                        case 307:
                        case 302:
                        case 301:
                            uri = new Uri(response.GetHeader("Location"));
                            if (OnRedirect != null)
                            {
                                OnRedirect(uri);
                                retry = maximumRedirects;
                            }
                            break;

                        default:
                            retry = maximumRedirects;
                            break;
                        }
                        //place the connection back into the pool if not upgraded.
                        if (upgradedConnection == null)
                        {
                            if (response.GetHeader("Connection").ToLower() != "keep-alive")
                            {
                                connection.stream.Close();
                            }
                            activeConnections [connection.key].Add(connection);
                        }
                    }
                    if (useCache)
                    {
                        string etag = response.GetHeader("etag");
                        if (etag.Length > 0)
                        {
                            etags [uri.AbsoluteUri] = etag;
                            SaveEtags();
                        }
                    }
                } catch (Exception e) {
                    exception = e;
                    response  = null;
                }
                state  = RequestState.Done;
                isDone = true;
            }));
        }
Esempio n. 11
0
        public void Send()
        {
            isDone = false;
            state  = RequestState.Waiting;
            if (acceptGzip)
            {
                SetHeader("Accept-Encoding", "gzip");
            }
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate {
                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();
                            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;
            }));
        }
Esempio n. 12
0
        /// <summary>
        /// 开始发送请求数据
        /// </summary>
        void BeginSending()
        {
            isDone = false;

            if (timeout > 0)
            {
                //开启超时协议检测
                UniWeb.Instance.StartCoroutine(Timeout());
            }
            //使用线程池请求数据
            System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                try
                {
                    //当前尝试重度的次数
                    var retryCount            = 0;
                    HttpConnection connection = null;

                    while (retryCount < maximumRedirects)
                    {
                        exception = null;
                        AddHeadersToRequest();
                        Uri pUri;
                        if (proxy != null)
                        {
                            pUri = proxy;
                        }
                        else
                        {
                            try
                            {
                                if (System.Net.WebRequest.DefaultWebProxy != null)
                                {
                                    pUri = System.Net.WebRequest.DefaultWebProxy.GetProxy(uri);
                                }
                                else
                                {
                                    pUri = uri;
                                }
                            }
                            catch (TypeInitializationException)
                            {
                                //Could not get WebRequest type... default to no proxy.
                                pUri = uri;
                            }
                        }

                        response = new Response(this);

                        try
                        {
                            connection = CreateConnection(pUri.Host, pUri.Port, pUri.Scheme.ToLower() == "https");
#if BNICKSON_UPDATED
                            WriteToStreamAsync(connection.stream);
#else
                            WriteToStream(connection.stream);
#endif
                            response.ReadFromStream(connection.stream, bodyStream);
                        }
                        catch (HTTPException ex)
                        {
                            EB.Debug.LogWarning("HTTPException {0}, retry ...", ex.Message);
                            exception = ex;
                            retryCount++;
                            continue;
                        }
                        catch (ObjectDisposedException ex)
                        {
                            EB.Debug.LogWarning("ObjectDisposedException {0}, retry ...", ex.Message);
                            exception = ex;
                            retryCount++;
                            continue;
                        }
                        catch (SocketException ex)
                        {
                            EB.Debug.LogWarning("SocketException {0}, retry ...", ex.Message);
                            exception = ex;
                            retryCount++;
                            continue;
                        }

                        string key          = string.Format("{0}:{1}", pUri.Host, pUri.Port);
                        connectionPool[key] = connection;

                        if (enableCookies)
                        {
                            foreach (var i in response.headers.GetAll("Set-Cookie"))
                            {
                                try
                                {
                                    cookies.SetCookies(uri, i);
                                }
                                catch (System.Net.CookieException)
                                {
                                    //Some cookies make the .NET cookie class barf. MEGH.
                                }
                            }
                        }
                        switch (response.status)
                        {
                        case 101:
                            upgradedConnection = connection;
                            break;

                        case 304:
                            break;

                        case 307:
                            uri = new Uri(response.headers.Get("Location"));
                            retryCount++;
                            continue;

                        case 302:
                        case 301:
                            method       = "GET";
                            var location = response.headers.Get("Location");
                            if (location.StartsWith("/"))
                            {
                                uri = new Uri(uri, location);
                            }
                            else
                            {
                                uri = new Uri(location);
                            }

                            retryCount++;
                            continue;

                        default:
                            break;
                        }

                        if (upgradedConnection == null)
                        {
                            if (response.protocol.ToUpper() == "HTTP/1.0" || response.headers.Get("Connection").ToUpper() == "CLOSE")
                            {
                                if (connectionPool.ContainsKey(key))
                                {
                                    connectionPool.Remove(key);
                                }
                                connection.Dispose();
                            }
                        }
                        break;
                    }

                    if (useCache && response != null)
                    {
                        var etag = response.headers.Get("etag");
                        if (etag.Length > 0)
                        {
                            etags[uri.AbsoluteUri] = etag;
                        }
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                    response  = null;
                }

                isDone = true;
            });
        }
Esempio n. 13
0
		private void SendFunction(System.Object t) {
			Debug.Log("SendFunction 0 ");
			try {
				var retry = 0;
				Debug.Log("Send 1 ");
				while (++retry < maximumRetryCount) {
					Debug.Log("Send 2 ");
					if (useCache) {
						string etag = "";
						if (etags.TryGetValue (uri.AbsoluteUri, out etag)) {
							SetHeader ("If-None-Match", etag);
						}
					}
					Debug.Log("Send 3 ");
					
					SetHeader ("Host", uri.Host);
					var client = new TcpClient ();
					client.Connect (uri.Host, uri.Port);
					Debug.Log("Send 4 ");
					using (var stream = client.GetStream ()) {
						Debug.Log("Send 5 ");
						
						var ostream = stream as Stream;
						if (uri.Scheme.ToLower() == "https") {
							Debug.Log("Send 6 ");
							
							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;
							}
						}
						Debug.Log("Send 7 ");
						
						WriteToStream (ostream);
						response = new Response ();
						state = RequestState.Reading;
						response.ReadFromStream(ostream);
					}
					Debug.Log("Send 8 ");
					
					client.Close ();
					switch (response.status) {
					case 307:
					case 302:
					case 301:
						uri = new Uri (response.GetHeader ("Location"));
						continue;
					default:
						retry = maximumRetryCount;
						break;
					}
					Debug.Log("Send 9 ");
					
				}
				Debug.Log("Send 10 ");
				
				if (useCache) {
					string etag = response.GetHeader ("etag");
					if (etag.Length > 0)
						etags[uri.AbsoluteUri] = etag;
				}
				Debug.Log("Send 11 ");
				
			} catch (Exception e) {
				Debug.Log("Send 12 ");
				
				Debug.LogException(e);
				Debug.LogError(e.Message);
				exception = e;
				response = null;
			}
			Debug.Log("Send 13 ");
			
			state = RequestState.Done;
			isDone = true;
		}