NetWrok.HTTP.Response.ReadFromStream C# (CSharp) Method

ReadFromStream() public method

public ReadFromStream ( Stream inputStream, Stream bodyStream ) : void
inputStream Stream
bodyStream Stream
return void
        public void ReadFromStream(Stream inputStream, Stream bodyStream)
        {
            progress = 0;

            if (inputStream == null) {
                throw new HTTPException ("Cannot read from server, server probably dropped the connection.");
            }
            var top = Protocol.ReadLine (inputStream).Split (' ');

            status = -1;
            int _status = -1;
            if (!(top.Length > 0 && int.TryParse (top [1], out _status))) {
                throw new HTTPException ("Bad Status Code, server probably dropped the connection.");
            }
            status = _status;
            message = string.Join (" ", top, 2, top.Length - 2);
            protocol = top[0];
            Protocol.CollectHeaders (inputStream, headers);

            if (status == 101) {
                progress = 1;
                return;
            }

            if (status == 204) {
                progress = 1;
                return;
            }

            if (status == 304) {
                progress = 1;
                return;
            }

            var chunked = headers.Get ("Transfer-Encoding").ToLower() == "chunked";

            /*
            //This code would break requests coming from HTTP/1.0

            if(!chunked && !headers.Contains("Content-Length")) {
                progress = 1;
                return;
            }
            */

            if(this.request.method.ToLower() == "head") {
                progress = 1;
                return;
            }

            Stream output = (Stream)bodyStream;
            if(output == null) {
                output = new MemoryStream();
            }

            if (chunked) {
                Protocol.ReadChunks (inputStream, output, ref progress);
                Protocol.CollectHeaders (inputStream, headers); //Trailers
            } else {
                Protocol.ReadBody (inputStream, output, headers, false, ref progress);
            }

            if(bodyStream == null) {
                output.Seek (0, SeekOrigin.Begin);
                Stream outputStream = output;

                var zipped = headers.Get ("Content-Encoding").ToLower() == "gzip";
                if(zipped) {
                    outputStream = new GZipStream (output, CompressionMode.Decompress);
                } else {
                    outputStream = output;
                }

                bytes = new byte[0];
                var buffer = new byte[1024];
                var count = -1;
                while (count != 0) {
                    count = outputStream.Read (buffer, 0, buffer.Length);
                    var offset = bytes.Length;
                    Array.Resize<byte> (ref bytes, offset + count);
                    Array.Copy (buffer, 0, bytes, offset, count);
                }
                outputStream.Dispose();
            }
        }

Usage Example

Example #1
0
        void BeginSending()
        {
            isDone = false;

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

            System.Threading.ThreadPool.QueueUserWorkItem (delegate(object state) {

                try {
                    var retryCount = 0;
                    Connection connection = null;

                    while (retryCount < maximumRedirects) {
                        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;
                            }

                        }

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

                        WriteToStream (connection.stream);

                        response = new Response (this);

                        try {

                            response.ReadFromStream (connection.stream, bodyStream);

                        } catch (HTTPException) {

                            retryCount ++;
                            continue;
                        }

                        connectionPool[pUri.Host] = 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;
                        }
                        break;
                    }

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

                    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;
            });
        }