Get() 공개 메소드

public Get ( int index ) : string
index int
리턴 string
예제 #1
0
        void FillCookies()
        {
            if (webHeaders == null)
            {
                return;
            }

            //
            // Don't terminate response reading on bad cookie value
            //
            string value;

            try {
                value = webHeaders.Get("Set-Cookie");
                if (value != null && SetCookie(value))
                {
                    return;
                }
            } catch {
            }

            try {
                value = webHeaders.Get("Set-Cookie2");
                if (value != null)
                {
                    SetCookie(value);
                }
            } catch {
            }
        }
 public static void SetHeaders(this WebHeaderCollection target, WebHeaderCollection headers)
 {
     foreach (var key in headers.AllKeys)
     {
         target.SetHeaderValue(key, headers.Get(key));
     }
 }
예제 #3
0
 protected static int GetContentLength(WebHeaderCollection responseHeaders)
 {
     int contentLength;
     //get the content length (if present)
     //Will return 0 if can't get value
     string clenString = responseHeaders.Get("Content-Length");
     //string clenString = response.GetResponseHeader("Content-Lengthzzz");
     int.TryParse(clenString, out contentLength);
     return contentLength;
 }
예제 #4
0
        void FillCookies()
        {
            if (webHeaders == null)
            {
                return;
            }

            //
            // Don't terminate response reading on bad cookie value
            //
            string           value;
            CookieCollection cookies = null;

            try {
                value = webHeaders.Get("Set-Cookie");
                if (value != null)
                {
                    cookies = cookie_container.CookieCutter(uri, HttpKnownHeaderNames.SetCookie, value, false);
                }
            } catch {
            }

            try {
                value = webHeaders.Get("Set-Cookie2");
                if (value != null)
                {
                    var cookies2 = cookie_container.CookieCutter(uri, HttpKnownHeaderNames.SetCookie2, value, false);

                    if (cookies != null && cookies.Count != 0)
                    {
                        cookies.Add(cookies2);
                    }
                    else
                    {
                        cookies = cookies2;
                    }
                }
            } catch {
            }

            this.cookieCollection = cookies;
        }
예제 #5
0
        void FillCookies()
        {
            if (webHeaders == null)
            {
                return;
            }

            string value = webHeaders.Get("Set-Cookie");

            if (value != null)
            {
                SetCookie(value);
            }

            value = webHeaders.Get("Set-Cookie2");
            if (value != null)
            {
                SetCookie(value);
            }
        }
예제 #6
0
        void INTERNAL_AddNewCookiesInContainer_SimulatorOnly(CookiesContainer container)
        {
            if (Interop.IsRunningInTheSimulator)
            {
                // never execute this code if not in simulator

                WebHeaderCollection myWebHeaderCollection = base.ResponseHeaders;

                if (myWebHeaderCollection != null) // the headers can be null if the response has crashed for some reason
                {
                    string allowOrigin       = myWebHeaderCollection.Get("Access-Control-Allow-Origin");
                    bool   wrongAccessOrigin = (allowOrigin == "*" || allowOrigin == string.Empty || allowOrigin == null);

                    // if wrongAccessOrigin, we assume that credentials are not supported. Less restrictions in simulator than JS
                    if (!wrongAccessOrigin)
                    {
                        // in javascript, this will always be null, but cookies are handled in another way
                        string Header = myWebHeaderCollection.Get("Set-Cookie");

                        if (Header != null)
                        {
                            string[] cookies = Header.Split(',');

                            foreach (string cookie in cookies)
                            {
                                // normally the container is an HashSet, so we don't need to check if the cookie is already in it.
                                if (cookie.Contains("ASP.NET")) // the .NET id cookie
                                {
                                    container.LastSessionId = cookie;
                                }
                                else
                                {
                                    container.Cookies.Add(cookie);
                                }
                            }
                        }
                    }
                    // else does not mean error, it just means that credentials are not supported on this response
                }
            }
        }
예제 #7
0
        public string GetHeadersString(WebHeaderCollection header = null)
        {
            if (header == null)
            {
                header = _header;
            }
            if (header.IsNullOrEmpty())
            {
                return(string.Empty);
            }

            var sb = new StringBuilder();

            sb.AppendFormat(HeaderFormat, _header.GetKey(0), _header.Get(0));
            for (int i = 1; i < _header.Count; i++)
            {
                sb.Append(Environment.NewLine)
                .AppendFormat(HeaderFormat, _header.GetKey(i), _header.Get(i));
            }
            return(sb.ToString());
        }
 private static Dictionary<string, string> GetHeadersDictionaryFrom(WebHeaderCollection headers)
 {
     string pattern = "\\s+";
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     for (int i = 0; i < headers.Keys.Count; i++)
     {
         string key = headers.GetKey(i).Replace("-", " ").ToUpper();
         key = Regex.Replace(key, pattern, "");
         string value = headers.Get(headers.GetKey(i));
         //System.Console.WriteLine("Key => " + key + " Value => " + value);
         dictionary.Add(key, value);
     }
     return dictionary;
 }
예제 #9
0
        void m_Start()
        {
            var type     = cRequest.assetType;
            var userData = cRequest.uploadData;

            if (LoaderType.Typeof_AssetBundle.Equals(type))
            {
                m_webrequest = UnityWebRequest.GetAssetBundle(cRequest.url);
            }
            if (LoaderType.Typeof_Texture2D.Equals(type))
            {
#if UNITY_2017
                m_webrequest = UnityWebRequestTexture.GetTexture(cRequest.url);
#else
                m_webrequest = UnityWebRequest.GetTexture(cRequest.url);
#endif
            }
            else if (userData is WWWForm)
            {
                m_webrequest = UnityWebRequest.Post(cRequest.url, (WWWForm)userData);
            }
            else if (userData is string)
            {
                var bytes = LuaHelper.GetBytes(userData.ToString());
                m_webrequest = UnityWebRequest.Put(cRequest.url, bytes);
            }
            else if (userData is System.Array)
            {
                m_webrequest = UnityWebRequest.Put(cRequest.url, (byte[])userData);
            }
            else
            {
                m_webrequest = UnityWebRequest.Get(cRequest.url);
            }

            System.Net.WebHeaderCollection headers = cRequest.webHeader;

            if (headers != null)
            {
                foreach (var k in headers.AllKeys)
                {
                    m_webrequest.SetRequestHeader(k, headers.Get(k));
                }
            }

            m_asyncOperation = m_webrequest.Send();
        }
        public SessionCommand(JsonObject response, WebHeaderCollection headers)
        {
            TransmissionDaemonDescriptor descriptor = new TransmissionDaemonDescriptor();
            JsonObject arguments = (JsonObject)response[ProtocolConstants.KEY_ARGUMENTS];
            if (arguments.Contains("version"))
                ParseVersionAndRevisionResponse((string)arguments["version"], descriptor);
            else if (headers.Get("Server") != null)
                descriptor.Version = 1.40;
            else
                descriptor.Version = 1.39;

            if (arguments.Contains("rpc-version"))
                descriptor.RpcVersion = Toolbox.ToInt(arguments["rpc-version"]);

            if (arguments.Contains("rpc-version-minimum"))
                descriptor.RpcVersionMin = Toolbox.ToInt(arguments["rpc-version-minimum"]);

            descriptor.SessionData = (JsonObject)response[ProtocolConstants.KEY_ARGUMENTS];
            Program.DaemonDescriptor = descriptor;
        }
예제 #11
0
        static string FormatHeaders(WebHeaderCollection headers)
        {
            var sb = new StringBuilder();

            for (int i = 0; i < headers.Count; i++)
            {
                string key = headers.GetKey(i);
                if (WebHeaderCollection.AllowMultiValues(key))
                {
                    foreach (string v in headers.GetValues(i))
                    {
                        sb.Append(key).Append(": ").Append(v).Append("\r\n");
                    }
                }
                else
                {
                    sb.Append(key).Append(": ").Append(headers.Get(i)).Append("\r\n");
                }
            }

            return(sb.Append("\r\n").ToString());
        }
예제 #12
0
        public static string GetPage(string url, string method, string contentType, SortedList<string, string> values, ref WebHeaderCollection responseHeaders)
        {
            string tmp = string.Empty;
            try
            {
                HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(url);
                wReq.UserAgent = "FlowLib";

            #if !COMPACT_FRAMEWORK
                wReq.CookieContainer = new CookieContainer();
                // Enable cookie support
                if (responseHeaders != null && responseHeaders.HasKeys())
                {
                    string str = responseHeaders.Get("Set-Cookie");
                    if (!string.IsNullOrEmpty(str))
                    {
                        string[] tmp2= str.Split('=', ' ', ';', ',', '\t', '\n', '\r');

                        if (tmp2.Length >= 2){
                            Cookie cookie = new Cookie(tmp2[0], tmp2[1]);
                            wReq.CookieContainer.Add(wReq.RequestUri, cookie);
                        }
                        //wReq.CookieContainer.Add(new Cookie(
                        //wReq.Headers.Add("Cookie", str);

                        //wReq.Headers.Set("Cookie", str);
                    }
                }
            #endif

                if (!string.IsNullOrEmpty(method) && !string.IsNullOrEmpty(contentType) && values != null)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (KeyValuePair<string, string> var in values)
                    {
                        sb.Append("&");
                        sb.Append(var.Key);
                        sb.Append("=");
                        sb.Append(var.Value);
                    }
                    byte[] data = Encoding.UTF8.GetBytes(sb.ToString());

                    // Set values for the request back
                    wReq.Method = method;
                    wReq.ContentType = contentType;
                    wReq.ContentLength = data.Length;

                    // Write to request stream.
                    Stream streamOut = wReq.GetRequestStream();
                    streamOut.Write(data, 0, data.Length);
                    streamOut.Flush();
                    streamOut.Close();
                }

                // Get the response stream.
                WebResponse wResp = wReq.GetResponse();
                Stream respStream = wResp.GetResponseStream();
                StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
                tmp = reader.ReadToEnd();

                responseHeaders = wResp.Headers;

                // Close the response and response stream.
                wResp.Close();
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
            return tmp;
        }
예제 #13
0
		public void GetValues ()
		{
			WebHeaderCollection w = new WebHeaderCollection ();
			w.Add ("Hello", "H1");
			w.Add ("Hello", "H2");
			w.Add ("Hello", "H3,H4");

			string [] sa = w.GetValues ("Hello");
			Assert.AreEqual (3, sa.Length, "#1");
			Assert.AreEqual ("H1,H2,H3,H4", w.Get ("Hello"), "#2");

			w = new WebHeaderCollection ();
			w.Add ("Accept", "H1");
			w.Add ("Accept", "H2");
			w.Add ("Accept", "H3,  H4  ");
			Assert.AreEqual (3, w.GetValues (0).Length, "#3a");
			Assert.AreEqual (4, w.GetValues ("Accept").Length, "#3b");
			Assert.AreEqual ("H4", w.GetValues ("Accept")[3], "#3c");
			Assert.AreEqual ("H1,H2,H3,  H4", w.Get ("Accept"), "#4");

			w = new WebHeaderCollection ();
			w.Add ("Allow", "H1");
			w.Add ("Allow", "H2");
			w.Add ("Allow", "H3,H4");
			sa = w.GetValues ("Allow");
			Assert.AreEqual (4, sa.Length, "#5");
			Assert.AreEqual ("H1,H2,H3,H4", w.Get ("Allow"), "#6");

			w = new WebHeaderCollection ();
			w.Add ("AUTHorization", "H1, H2, H3");
			sa = w.GetValues ("authorization");
			Assert.AreEqual (3, sa.Length, "#9");

			w = new WebHeaderCollection ();
			w.Add ("proxy-authenticate", "H1, H2, H3");
			sa = w.GetValues ("Proxy-Authenticate");
			Assert.AreEqual (3, sa.Length, "#9");

			w = new WebHeaderCollection ();
			w.Add ("expect", "H1,\tH2,   H3  ");
			sa = w.GetValues ("EXPECT");
			Assert.AreEqual (3, sa.Length, "#10");
			Assert.AreEqual ("H2", sa [1], "#11");
			Assert.AreEqual ("H3", sa [2], "#12");

			try {
				w.GetValues (null);
				Assert.Fail ("#13");
			} catch (ArgumentNullException) { }
			Assert.AreEqual (null, w.GetValues (""), "#14");
			Assert.AreEqual (null, w.GetValues ("NotExistent"), "#15");

			w = new WebHeaderCollection ();
			w.Add ("Accept", null);
			Assert.AreEqual (1, w.GetValues ("Accept").Length, "#16");

			w = new WebHeaderCollection ();
			w.Add ("Accept", ",,,");
			Assert.AreEqual (3, w.GetValues ("Accept").Length, "#17");
		}
예제 #14
0
 private Encoding GetHttpResponseEncoding(WebHeaderCollection headers)
 {
     Encoding encoding = Encoding.UTF8; // use UTF-8 by default.
     string contentType = headers.Get(Constants.ContentType);
     if (contentType != null) // expected form: "text/html; charset=utf-8".
     {
         string[] keyValuePairs = contentType.Split(';');
         foreach (string[] kvp in keyValuePairs.Select(kvp => kvp.Split('=')))
         {
             if (kvp.Length == 2 && kvp[0].Trim().ToLowerInvariant() == Constants.CharsetEncodingHeader)
             {
                 return Encoding.GetEncoding(kvp[1]); // use the response header encoding.
             }
         }
     }
     return encoding;
 }
        private bool TryParseRetryAfter(WebHeaderCollection headers, out TimeSpan retryAfterTimeSpan)
        {
            retryAfterTimeSpan = TimeSpan.FromSeconds(0);
            var retryAfter = headers.Get("Retry-After");
            if (retryAfter == null)
            {
                return false;
            }

            var now = DateTime.Now;
            DateTime retryAfterDate;
            if (DateTime.TryParse(retryAfter, out retryAfterDate))
            {
                if (retryAfterDate > now)
                {
                    retryAfterTimeSpan = retryAfterDate - now;
                    return true;
                }
                else
                {
                    return false;
                }
            }

            TelemetryChannelEventSource.Log.TransmissionPolicyRetryAfterParseFailedWarning(retryAfter);

            return false;
        }
예제 #16
0
        private WebHeaderCollection ProcessHeaderStream(HttpRequest request, CookieContainer cookies, Stream headerStream)
        {
            headerStream.Position = 0;
            var headerData = headerStream.ToBytes();
            var headerString = Encoding.ASCII.GetString(headerData);

            var webHeaderCollection = new WebHeaderCollection();

            // following a redirect we could have two sets of headers, so only process the last one
            foreach (var header in headerString.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Reverse())
            {
                if (!header.Contains(":")) break;
                webHeaderCollection.Add(header);
            }

            var setCookie = webHeaderCollection.Get("Set-Cookie");
            if (setCookie != null && setCookie.Length > 0 && cookies != null)
            {
                try
                {
                    cookies.SetCookies((Uri)request.Url, FixSetCookieHeader(setCookie));
                }
                catch (CookieException ex)
                {
                    _logger.Debug("Rejected cookie {0}: {1}", ex.InnerException.Message, setCookie);
                }
            }

            return webHeaderCollection;
        }
예제 #17
0
 public SessionEvent(byte[] responseBytes, WebHeaderCollection responseHeaders,
     String uri, String capsKey, String proto)
     : base()
 {
     this.Protocol = proto;
     this.Direction = Direction.Incoming; // EventQueue Messages are always inbound from the simulator
     this.ResponseBytes = responseBytes;
     this.ResponseHeaders = responseHeaders;
     this.Host = uri;
     this.Name = capsKey;
     this.ContentType = responseHeaders.Get("Content-Type");
     this.Length = Int32.Parse(responseHeaders.Get("Content-Length"));
 }
        /// <summary>
        /// Receives the continue header from delegate and sets it to ContinueHeader property.
        /// </summary>
        /// <param name="statusCode"> The status code</param>
        /// <param name="header"> The header collection.</param>
        protected void GetRedirectHeaders(int statusCode, WebHeaderCollection header)
        {
            StringBuilder textStream = new StringBuilder();

            for (int i = 0;i<header.Count;i++)
            {
                textStream.Append(header.GetKey(i));
                textStream.Append(": ");
                textStream.Append(header.Get(i));
                textStream.Append("\r\n");
            }

            ContinueHeader= textStream.ToString();
        }
예제 #19
0
파일: Request.cs 프로젝트: JerryXia/ML
 void SetHeaders(WebHeaderCollection headers)
 {
     if (headers != null && headers.Count > 0)
     {
         foreach (string item in headers.AllKeys)
         {
             request.Headers.Add(item, headers.Get(item));
         }
     }
 }
예제 #20
0
 public void ResetCookie(WebHeaderCollection whc, string host)
 {
     for (int i = 0; i < whc.Count; i++) {
         string key = whc.GetKey(i);
         string value = whc.Get(i);
         if (key == "Set-Cookie") {
             Match match = Regex.Match(value, "(.+?)=(.+?);");
             if (match.Captures.Count > 0) {
                 cookieContainer.Add(new Cookie(match.Groups[1].Value, match.Groups[2].Value, "/", host.Split(':')[0]));
             }
         }
     }
 }
예제 #21
0
		static string FormatHeaders (WebHeaderCollection headers)
		{
			var sb = new StringBuilder();

			for (int i = 0; i < headers.Count ; i++) {
				string key = headers.GetKey (i);
				if (WebHeaderCollection.AllowMultiValues (key)) {
					foreach (string v in headers.GetValues (i)) {
						sb.Append (key).Append (": ").Append (v).Append ("\r\n");
					}
				} else {
					sb.Append (key).Append (": ").Append (headers.Get (i)).Append ("\r\n");
				}
			}

			return sb.Append("\r\n").ToString();
		}
예제 #22
0
        /// <summary>
        /// Handle response headers
        /// </summary>
        private void HandleHeader(string url, WebHeaderCollection headers)
        {
            for (int i = 0; i < headers.Count; i++)
            {
                string Key = headers.GetKey(i);
                string Value = headers.Get(i);

                switch (Key)
                {
                    case "Set-Cookie":
                        HandleResponseSetCookie(url, Value);
                        break;
                    case "Location":
                        this.RedirectLocation = Value;
                        break;
                }
            }
        }
예제 #23
0
        public string ParseHeader(WebHeaderCollection headers)
        {
            StringBuilder builder = new StringBuilder();

            if (headers != null)
            {
                foreach (var item in headers.AllKeys)
                {
                    builder.AppendFormat("{0} : {1}{2}", item, headers.Get(item), Environment.NewLine);
                }
            }

            return builder.ToString();
        }
예제 #24
0
        public static string CrawlIt(this string url, Encoding encoding, WebHeaderCollection headers = null, CookieContainer cookieContainer = null, int timeout = 3000)
        {
            var tryCount = 0;
            while (true)
            {
                try
                {
                    var webRequest = (HttpWebRequest)WebRequest.Create(url);
                    webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
                    webRequest.CookieContainer = cookieContainer == null ? new CookieContainer() : cookieContainer;

                    if ( headers != null )
                    {
                        foreach( String key in headers.Keys )
                        {
                            switch ( key )
                            {
                                // referer는 Header 컬렉션에 포함되지 않고 별도로 취급되므로 따로 빼놓기.
                                case "Referer":
                                    webRequest.Referer = headers.Get(key);
                                    break;
                                default:
                                    webRequest.Headers.Set(key, headers.Get(key));
                                    break;
                            }
                        }
                    }

                    webRequest.AllowAutoRedirect = true;
                    webRequest.Timeout = timeout;

                    using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
                    using (var reader = new StreamReader(webResponse.GetResponseStream(), encoding))
                    {
                        var rawHtml = reader.ReadToEnd();
                        var statusCode = webResponse.StatusCode;

                        return rawHtml;
                    }
                }
                catch (WebException ex)
                {
                    Logger.Log(new Exception(url) { Source = ex.Source });
                    Logger.Log(ex);
                    tryCount++;

                    // 3번 시도한 후 안될 경우 더 이상 시도하지 않음
                    if (tryCount == 3)
                        throw;
                }
            }
        }
예제 #25
0
        private void ThreadLoop()
        {
            while (true)
            {
                if (Socket != null) Socket.Close(); // securité: on ferme l'eventuelle Socket précédente
                try
                {
                    Socket = tcpListener.AcceptSocket();
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.Interrupted)
                        return; // arrêt du serveur
                    throw;
                }
                if (ValidateRemoteAddr((Socket.RemoteEndPoint as IPEndPoint).Address))
                try
                {
                    NetworkStream networkStream = new NetworkStream(Socket, true);
                    networkStream.ReadTimeout = 1000; // timeout if read doesn't succeed after 1 sec
                    using (RequestContent = new StreamReader(networkStream, Encoding.Default))
                    {
                        string line = null;
                        int index;
                        ProtocolVersion = HttpVersion.Version10;
                        HttpStatusCode StatusCode;// = HttpStatusCode.OK;
                        ErrorDescription = null;
                        Url = null;
                        Query = null;
                        QueryArgs = null;
                        LastModified = DateTime.Now;
                        ResponseHeaders = new WebHeaderCollection();
                        ContentType = new ContentType("text/html");
                        ContentLength = -1;
                        Content = null;
                        try
                        {
                            try
                            {
                                line = RequestContent.ReadLine();
                            }
                            catch (IOException e)
                            {
                                throw new ApplicationException(e.Message, e);
                            }
                            Console.WriteLine("HTTP< " + line);
                            if (line == null) continue;
                            index = line.IndexOf(' ');
                            HttpMethod = line.Substring(0, index);
                            line = line.Substring(index + 1);
                            index = line.IndexOf(' ');
                            if (index >= 0)
                            {
                                string protocolVersion = line.Substring(index + 1);
                                Match m = (new Regex("HTTP/(\\d+).(\\d+)")).Match(protocolVersion);
                                if (!m.Success) throw new Exception("Protocole HTTP invalide");
                                line = line.Substring(0, index);
                                ProtocolVersion = new Version(Convert.ToInt32(m.Groups[1].Value), Convert.ToInt32(m.Groups[2].Value));
                            }
                            else
                                ProtocolVersion = HttpVersion.Version10;
                            if (line.Length == 0) throw new Exception("URI manquante");
                            index = line.IndexOf('?');
                            if (index >= 0)
                            {
                                Query = line.Substring(index);
                                QueryArgs = System.Web.HttpUtility.ParseQueryString(System.Web.HttpUtility.HtmlDecode(line.Substring(index + 1)));
                                line = line.Substring(0, index);
                            }
                            else
                            {
                                Query = String.Empty;
                                QueryArgs = new NameValueCollection();
                            }
                            Url = line;

                            Accept = null;
                            Connection = null;
                            RequestContentLength = -1;
                            RequestContentType = null;
                            Host = null;
                            IfModifiedSince = new DateTime(); // DateTime vide
                            Referer = null;
                            UserAgent = null;
                            RequestHeaders = new WebHeaderCollection();
                            while ((line = RequestContent.ReadLine()).Length != 0)
                            {
                                index = line.IndexOf(':');
                                if (index < 0)
                                {
                                    Console.WriteLine("BasicHttpServer: Header HTTP invalide: " + line);
                                    continue;
                                }
                                string headerName = line.Substring(0, index);
                                line = line.Substring(index + 1).Trim();
                                switch (headerName.ToLower())
                                {
                                    case "accept": Accept = line; break;
                                    case "connection": Connection = line; break;
                                    case "content-length": RequestContentLength = Convert.ToInt64(line); break;
                                    case "content-type": RequestContentType = new ContentType(line); break;
                                    case "host": Host = line; break;
                                    case "if-modified-since": IfModifiedSince = DateTime.Parse(line); break;
                                    case "referer": Referer = line; Console.WriteLine("HTTP< Referer: " + line); break;
                                    case "user-agent": UserAgent = line; break;
                                    default:
                                        Console.WriteLine("BasicHttpServer: Header inconnu: {0}: {1}", headerName, line);
                                        RequestHeaders.Add(headerName, line);
                                        break;
                                }
                            }

                            try
                            {
                                // handle the request (this function is eventually overriden)
                                StatusCode = HandleRequest();
                                if (StatusCode != HttpStatusCode.OK)
                                    Console.WriteLine("BasicHttpServer: {0} {1}: {2}\r\n\t{3}", (int) StatusCode, StatusCode, Url, ErrorDescription);
                            }
            #if DEBUG
                            catch (ApplicationException e)
            #else
                            catch (Exception e) // en mode RELEASE, catch toutes les exceptions pour ne pas planter le serveur
            #endif
                            {
                                StatusCode = HttpStatusCode.InternalServerError;
                                ErrorDescription = e.Message;
                                Console.WriteLine("BasicHttpServer: {0}:\r\n\tsur la requete {1}{2}", e, Url, Query);
                            }
                        }
            #if DEBUG
                        catch (ApplicationException e)
            #else
                        catch (Exception e) // en mode RELEASE, catch toutes les exceptions pour ne pas planter le serveur
            #endif
                        {
                            StatusCode = HttpStatusCode.BadRequest;
                            ErrorDescription = e.Message;
                            Console.WriteLine("BasicHttpServer: {0}:\r\nsur le parsing de {1}", e, line);
                        }
                        if ((Content == null) && (StatusCode != HttpStatusCode.OK))
                        {
                            ContentType = new ContentType("text/html");
                            ReplyFormattedFile(ErrorFile, (int)StatusCode, StatusCode, Url, ErrorDescription.Replace("\r\n", "<br>"));
                        }

                        if (HackStatusCodeAlwaysOK) // cas particulier des clients HTTP qui n'aiment pas autre chose qu'OK (ex: Freebox ...)
                            StatusCode = HttpStatusCode.OK;

                        // envoi des Headers de la réponse
                        StreamWriter writer = new StreamWriter(networkStream, Encoding.Default);
                        writer.WriteLine("HTTP/{0}.{1} {2} {3}", ProtocolVersion.Major, ProtocolVersion.Minor,
                                                                (int)StatusCode, StatusCode);
                        writer.WriteLine("Last-Modified: " + LastModified.ToString("R"));
                        writer.WriteLine("Location: " + ResponseUri);
                        if (ProtocolVersion > HttpVersion.Version10)
                        {
                            writer.WriteLine("Connection: close"); // c'est un serveur vraiment basique... pas de Keep-Alive
                            for (index = 0; index < ResponseHeaders.Count; index++)
                                writer.WriteLine("{0}: {1}", ResponseHeaders.GetKey(index), ResponseHeaders.Get(index));
                        }
                        if (Content != null)
                        {
                            writer.WriteLine("Content-Type: " + ContentType);
                            //Console.WriteLine("HTTP> Content-Type: " + ContentType);
                            if ((ContentLength == -1) && Content.CanSeek)
                                ContentLength = Content.Length;
                            if (ContentLength != -1)
                            {
                                writer.WriteLine("Content-Length: " + ContentLength);
                                //Console.WriteLine("HTTP> Content-Length: " + ContentLength);
                            }
                        }
                        writer.WriteLine(); // termine les headers avec une ligne vide
                        try
                        {
                            writer.Flush();
                        }
                        catch (IOException)
                        {
                        }

                        if (Content != null)
                        {
                            if (HttpMethod != "HEAD")
                                try
                                {
                                    // TODO: faire un choix sur le comportement si la position n'est pas au debut du Stream)
                                    // actuellement, pour MemoryStream, on balance tout depuis le debut, meme si la position n'est pas au debut
                                    // et pour les autres Stream, on balance à partir de la position en cours
                                    // (ce qui permet de n'envoyer qu'une portion précise si on veut)

                                    if ((Content is MemoryStream) && (ContentLength == Content.Length))
                                    { // variante optimisée pour les MemoryStream
                                        ((MemoryStream)Content).WriteTo(networkStream);
                                    }
                                    else if (ContentLength == -1)
                                    {
                                        byte[] buffer = new byte[4096L];
                                        do
                                        {
                                            index = Content.Read(buffer, 0, 4096);
                                            networkStream.Write(buffer, 0, index);
                                        } while (index != 0);
                                    }
                                    else
                                    {
                                        byte[] buffer = new byte[Math.Min(ContentLength, 4096L)];
                                        while (ContentLength > 0)
                                        {
                                            index = Content.Read(buffer, 0, buffer.Length);
                                            if (index == 0)
                                            {
                                                Console.WriteLine("BasicHttpServer: Supplied Content stream did not contain expected ContentLength");
                                                break;
                                            }
                                            networkStream.Write(buffer, 0, index);
                                            ContentLength -= index;
                                        }
                                    }
                                }
                                catch (IOException)
                                {
                                }
                            Content.Close();
                        } // if (Content != null)
                    } // using (content) => Terminate the connection

                    HandleAfterReply(); // opportunité de faire un traitement après que la réponse aie été envoyée
                }
            #if DEBUG
                catch (ApplicationException e)
            #else
                catch (Exception e) // en mode RELEASE, catch toutes les exceptions pour ne pas planter le serveur
            #endif
                {
                    Console.WriteLine("BasicHttpServer: " + e);
                }
            } // while
        }
예제 #26
0
        private WebHeaderCollection ProcessHeaderStream(HttpWebRequest webRequest, Stream headerStream)
        {
            headerStream.Position = 0;
            var headerData = headerStream.ToBytes();
            var headerString = Encoding.ASCII.GetString(headerData);

            var webHeaderCollection = new WebHeaderCollection();

            foreach (var header in headerString.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1))
            {
                webHeaderCollection.Add(header);
            }

            var setCookie = webHeaderCollection.Get("Set-Cookie");
            if (setCookie != null && setCookie.Length > 0 && webRequest.CookieContainer != null)
            {
                webRequest.CookieContainer.SetCookies(webRequest.RequestUri, setCookie);
            }

            return webHeaderCollection;
        }
예제 #27
0
파일: Form1.cs 프로젝트: HaleLu/GetPic
 private static void DisplayHeaders(WebHeaderCollection headers)
 {
     foreach (string key in headers.Keys)
         Trace.WriteLine(key + ":" + headers.Get(key));
 }