public CreateMultipartPieceResult FromHttpHeaders(WebHeaderCollection headers)
 {
     this.Status   = Convert.ToInt32(headers.Get("X-Agile-Status"));
     this.Size     = Convert.ToInt64(headers.Get("X-Agile-Size"));
     this.Checksum = headers.Get("X-Agile-Checksum");
     return(this);
 }
示例#2
0
        /// <summary>
        /// Méthode qui permet de préparer
        /// la partie CanonicalizedHeaders.
        /// </summary>
        /// <param name="request"><seealso cref="WebRequest"/></param>
        /// <returns></returns>
        public static string PrepareCanonicalizedHeaders(WebRequest request)
        {
            WebHeaderCollection         headers       = request.Headers;
            Dictionary <string, string> headersValues = new Dictionary <string, string>();

            foreach (var headername in headers.Keys)
            {
                bool isAmazParamHeader     = headername.ToString().ToLower().Contains("x-amz-");
                bool isAmazDateParamHeader = headername.ToString().ToLower().Contains("x-amz-date");
                if (isAmazParamHeader && !isAmazDateParamHeader)
                {
                    if (!headersValues.ContainsKey(headername.ToString().ToLower()))
                    {
                        headersValues.Add(headername.ToString().ToLower(), headers.Get(headername.ToString()).TrimEnd().TrimStart());
                    }
                    else
                    {
                        headersValues[headername.ToString().ToLower()] += "," + headers.Get(headername.ToString()).TrimEnd().TrimStart();
                    }


                    headersValues[headername.ToString().ToLower()].Replace("\\s+", " ");
                    headersValues[headername.ToString().ToLower()] += "\n";
                }
            }


            headersValues = headersValues.OrderBy(s => s.Key).ToDictionary(pair => pair.Key, pair => pair.Value);

            return(string.Join("", headersValues.Select(m => m.Key + ":" + m.Value).ToArray()));
        }
        /**
         * For requests that have defined a ResponseType of ResponseType.STREAMING, this
         * method will write the HTTP response body into the stream marked with the
         * MarketplaceWebServiceStream attribute, setting the StreamType to StreamType.RECEIVE_STREAM.
         * In addition to writing the response, the Content-MD5 returned by the service
         * will be compared for equality to a locally calculated value.
         *
         * Content-MD5 comparison failure will result in a MarketplaceWebServiceException to be
         * thrown.
         */
        private T HandleStreamingResponse <T>(HttpWebResponse webResponse, object clazz)
        {
            Stream receiverStream = GetTransferStream(clazz, StreamType.RECEIVE_STREAM);

            CopyStream(webResponse.GetResponseStream(), receiverStream);
            receiverStream.Position = 0;

            WebHeaderCollection headers = webResponse.Headers;
            string receivedContentMD5   = headers.Get("Content-MD5");
            string expectedContentMD5   = CalculateContentMD5(receiverStream);

            receiverStream.Position = 0;
            if (receivedContentMD5 != expectedContentMD5)
            {
                throw new MarketplaceWebServiceException(
                          "Received Content MD5 value " + receivedContentMD5 +
                          " doesn't match computed value " + expectedContentMD5 + ".");
            }

            IDictionary <String, String> parameters = new Dictionary <String, String>();

            parameters.Add("RequestId", headers.Get("x-amz-request-id"));
            parameters.Add("ContentMD5", headers.Get("Content-MD5"));

            return(DeserializeStreamingResponse <T>(parameters));
        }
 public void InitializeRequest(Uri url, Method method, WebHeaderCollection head, int timeout)
 {
     if (url.Scheme.ToLower() == "https")
     {
         ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) =>
         {
             return(true); //总是接受
         });
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
     }
     Request = WebRequest.Create(url) as HttpWebRequest;
     Request.AllowAutoRedirect = true;
     Request.KeepAlive         = false;
     Request.Method            = method.ToString();
     if (head.AllKeys.Contains("user-agent"))
     {
         Request.UserAgent = head.Get("user-agent");
         head.Remove("user-agent");
     }
     foreach (var item in head.AllKeys)
     {
         Request.Headers.Add(item, head.Get(item));
     }
     Request.ContentType = "charset=UTF-8;";
     Request.Timeout     = timeout;
 }
 public CreateMultipartResult FromHttpHeaders(WebHeaderCollection headers)
 {
     this.Status = Convert.ToInt32(headers.Get("X-Agile-Status"));
     this.MpId   = headers.Get("X-Agile-MultiPart");
     this.Path   = headers.Get("X-Agile-Path");
     return(this);
 }
 public MakeFileResult FromHttpHeaders(WebHeaderCollection headers)
 {
     this.Path     = headers.Get("X-Agile-Path");
     this.Status   = Convert.ToInt32(headers.Get("X-Agile-Status"));
     this.Size     = Convert.ToInt64(headers.Get("X-Agile-Size"));
     this.Checksum = headers.Get("X-Agile-Checksum");
     return(this);
 }
示例#7
0
        /// <summary>
        /// Prepara a requisição antes da solicitação
        /// </summary>
        /// <param name="request"></param>
        private void AddPostDataTo(HttpWebRequest request)
        {
            request.UserAgent = SettingsManager.GetSessionUserAgent();
            WebHeaderCollection myWebHeaderCollection = request.Headers;

            myWebHeaderCollection.Add("Accept-Language", SettingsManager.GetSessionAcceptLanguage());
            myWebHeaderCollection.Add("AcceptCharset", SettingsManager.GetSessionAcceptCharset());
            myWebHeaderCollection.Add("TransferEncoding", SettingsManager.GetSessionTransferEncoding());
            if (extraHeader != null)
            {
                foreach (var kv in extraHeader)
                {
                    if (myWebHeaderCollection.Get(kv.Key) == null)
                    {
                        myWebHeaderCollection.Add(kv.Key, kv.Value);
                    }
                }
            }
            if (toRemoveHeader != null)
            {
                foreach (var r in toRemoveHeader)
                {
                    if (myWebHeaderCollection.Get(r) != null)
                    {
                        myWebHeaderCollection.Remove(r);
                    }
                }
            }
            request.Referer           = lasUrl;
            request.AllowAutoRedirect = this.AutoRedirect;
            //request.KeepAlive = true;
            if (IsXMLPost)
            {
                string payload = XmlToPost;
                byte[] buff    = System.Text.Encoding.UTF8.GetBytes(payload);

                request.ContentLength = buff.Length;
                request.ContentType   = "text/plain; charset=UTF-8";

                System.IO.Stream reqStream = request.GetRequestStream();

                reqStream.Write(buff, 0, buff.Length);
            }
            else
            {
                string payload = FormElements.AssemblePostPayload();
                var    enc     = Encoding.GetEncoding("ISO-8859-1");

                byte[] buff = enc.GetBytes(payload.ToCharArray());

                request.ContentLength = buff.Length;
                request.ContentType   = "application/x-www-form-urlencoded";

                System.IO.Stream reqStream = request.GetRequestStream();

                reqStream.Write(buff, 0, buff.Length);
            }
        }
示例#8
0
        public void Get_Fail()
        {
            WebHeaderCollection w = new WebHeaderCollection();

            w.Add("Accept", "text/plain");

            Assert.Throws <ArgumentOutOfRangeException>(() => w.Get(-1));
            Assert.Throws <ArgumentOutOfRangeException>(() => w.Get(42));
        }
示例#9
0
        public byte[] DownloadBytes(string url)
        {
            var args = "";

            for (int i = 0; i < Headers.Count; i++)
            {
                args += "-H '" + Headers.GetKey(i) + ": " + Headers.Get(i) + "' ";
            }

            var cc = container.GetCookieHeader(new Uri(url));

            if (!string.IsNullOrEmpty(cc))
            {
                args += "-H '" + cc + "'";
            }

            if (args == "-H '")
            {
                args = "";
            }

            ProcessStartInfo start = new ProcessStartInfo();

            start.FileName               = "curl";
            start.Arguments              = args + url;
            start.UseShellExecute        = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError  = true;
            start.RedirectStandardInput  = false;
            start.CreateNoWindow         = true;

            Process p = Process.Start(start);

            p.WaitForExit();

            FileStream baseStream = p.StandardOutput.BaseStream as FileStream;

            byte[] bytes    = null;
            int    lastRead = 0;

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] buffer = new byte[4096];
                do
                {
                    lastRead = baseStream.Read(buffer, 0, buffer.Length);
                    ms.Write(buffer, 0, lastRead);
                } while (lastRead > 0);

                bytes = ms.ToArray();
                baseStream.Close();
                baseStream.Dispose();
            }

            p.WaitForExit();
            return(bytes);
        }
示例#10
0
        public static void DownLoadData(string url, string savePath)
        {
            WebHeaderCollection webHeaderCollection = GetDataHeader(url);

            bool ifRange = webHeaderCollection?.Get("Accept-Ranges") == "bytes";//是否支持range查询

            /*断点续传*/
            if (ifRange)
            {
                string fileName = webHeaderCollection?.Get("ETag")?.Replace("\"", "");                //ETag标识作为文件名称
                fileName = savePath + @"\" + fileName + ".zip";
                long historyFileLength = GetHistoryDataLength(fileName);                              //获取当前下载文件的已下载部分Length
                long.TryParse(webHeaderCollection.Get("Content-Length"), out long contentFileLength); //获取待下载文件的总文件Length

                /*分批次下载文件*/
                long perRange = 1024 * 10;//单次文件下载量
                while (historyFileLength < contentFileLength)
                {
                    string startRange           = historyFileLength.ToString();
                    long   endRangeShouldBe     = historyFileLength + perRange;
                    string endRange             = endRangeShouldBe > contentFileLength ? string.Empty : endRangeShouldBe.ToString();
                    WebHeaderCollection header2 = new WebHeaderCollection()
                    {
                        { "Range", "bytes=" + startRange + "-" + endRange }
                    };

                    var item2 = new HttpItem()
                    {
                        URL = url, Method = "GET", ResultType = ResultType.Byte, Header = header2
                    };
                    var result = GetHttpResult(item2)?.ResultByte;
                    historyFileLength += result?.LongLength ?? 0;

                    SaveDataToFile(fileName, result);

                    Console.WriteLine($"下载进度:{Math.Round((decimal)historyFileLength * 100 / contentFileLength, 2, MidpointRounding.AwayFromZero)}%");
                }
                Console.WriteLine($"下载进度:{Math.Round((decimal)historyFileLength * 100 / contentFileLength, 2, MidpointRounding.AwayFromZero)}%");
            }
            /*普通下载*/
            else
            {
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss");//ETag标识作为文件名称
                fileName = savePath + @"\" + fileName + ".zip";

                HttpItem httpItem = new HttpItem()
                {
                    URL        = url,
                    Method     = "GET",
                    ResultType = ResultType.Byte
                };
                var result = GetHttpResult(httpItem)?.ResultByte;
                SaveDataToFile(fileName, result);
            }
        }
示例#11
0
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="requestUrl">请求url</param>
        /// <param name="responseText">响应</param>
        /// <returns></returns>
        public HttpWebResponseResult Get(String requestUrl)
        {
            this.isPost            = false;
            this.requestUrl        = requestUrl;
            this.webResponseResult = new HttpWebResponseResult();

            webClient       = new WebClient();
            webClient.Proxy = null;

            #region //请求头部处理
            requestHeads.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
            foreach (var key in requestHeads.AllKeys)
            {
                webClient.Headers.Add(key, requestHeads.Get(key));
            }
            #endregion

            #region //请求数据
            byte[] responseBytes = null;
            String url           = GetFields();
            #endregion

            #region //发送请求
            try
            {
                responseBytes = webClient.DownloadData(url);
                webResponseResult.IsSuccess = true;
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    Stream responseStream = ex.Response.GetResponseStream();
                    responseBytes = new byte[responseStream.Length];
                    responseStream.Read(responseBytes, 0, responseBytes.Length);
                }
                else
                {
                    String errorMessage = ex.InnerException.Message;
                    responseBytes = encoding.GetBytes(errorMessage);
                }
                webResponseResult.IsSuccess = false;
            }
            #endregion

            webResponseResult.ResponseText     = System.Text.Encoding.UTF8.GetString(responseBytes);
            webResponseResult.RequestTraceInfo = TraceInfo();

            ResetStatus();

            return(webResponseResult);
        }
示例#12
0
        private static ServiceBusHttpMessage Receive(string httpVerb, string address, string token, ref string messageUri)
        {
            WebClient             webClient = CreateWebClient(token);
            ServiceBusHttpMessage message   = new ServiceBusHttpMessage();

            try
            {
                message.body = webClient.UploadData(address + "/messages/head?timeout=60", httpVerb, new byte[0]);
            }
            catch (WebException ex)
            {
                Console.WriteLine("Receive failed: " + GetErrorFromException(ex));
                return(null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Receive failed: " + ex.Message);
                return(null);
            }
            WebHeaderCollection responseHeaders = webClient.ResponseHeaders;

            // Check if a message was returned.
            if (responseHeaders.Get("BrokerProperties") == null)
            {
                return(null);
            }

            // Deserialize BrokerProperties.
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BrokerProperties));

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseHeaders["BrokerProperties"])))
            {
                message.brokerProperties = (BrokerProperties)serializer.ReadObject(ms);
            }

            // Get custom propoerties.
            foreach (string key in responseHeaders.AllKeys)
            {
                if (!key.Equals("Transfer-Encoding") && !key.Equals("BrokerProperties") && !key.Equals("Content-Type") && !key.Equals("Location") && !key.Equals("Date") && !key.Equals("Server"))
                {
                    message.customProperties.Add(key, responseHeaders[key]);
                }
            }

            // Get message URI.
            if (responseHeaders.Get("Location") != null)
            {
                messageUri = responseHeaders["Location"];
            }

            return(message);
        }
示例#13
0
        public ResponseEntity GetVideoBytes([PathParam] string videoName, [Injected] WebHeaderCollection headers)
        {
            if (headers.Get("Range") == null)
            {
                throw new Exception("No range header present");
            }
            var           range     = helperFunctions.RangeHeaderToBytes(headers.Get("Range"));
            var           videoData = videoServices.GetBytes(videoName, range.upper, range.lower);
            var           remaining = videoData.totalSize - videoData.upper;
            VideoByteData data      = new VideoByteData(videoData.videoData, remaining);

            return(new ResponseEntity(data, Headers));
        }
 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"));
 }
示例#15
0
 public Header(WebHeaderCollection webHeaderCollection)
 {
     accept         = webHeaderCollection.Get("Accept");
     acceptCharset  = webHeaderCollection.Get("Accept-Charset");
     acceptEncoding = webHeaderCollection.Get("Accept-Encoding");
     acceptLanguage = webHeaderCollection.Get("Accept-Language");
     allow          = webHeaderCollection.Get("Allow");
     authorization  = webHeaderCollection.Get("Authorization");
     cookie         = webHeaderCollection.Get("Cookie");
     from           = webHeaderCollection.Get("From");
     userAgent      = webHeaderCollection.Get("User-Agent");
 }
示例#16
0
        /// <summary>
        /// Event handler for HtmlWeb.PreRequestHandler. Occurs before an HTTP request is executed.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected bool OnPreRequest(HttpWebRequest request)
        {
            WebHeaderCollection myWebHeaderCollection = request.Headers;

            if (_useCredential)
            {
                request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
                request.Credentials         = _credentials;
            }
            request.AllowAutoRedirect = _autoRedirect;
            request.UserAgent         = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:65.0) Gecko/20100101 Firefox/65.0";
            myWebHeaderCollection.Add("Accept-Language", "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3");
            myWebHeaderCollection.Add("AcceptCharset", "ISO-8859-1,utf-8;q=0.8,*;q=0.8");
            myWebHeaderCollection.Add("TransferEncoding", "gzip,deflate");

            if (_extraHeader != null)
            {
                foreach (var kv in _extraHeader)
                {
                    if (myWebHeaderCollection.Get(kv.Key) == null)
                    {
                        myWebHeaderCollection.Add(kv.Key, kv.Value);
                    }
                }
            }
            if (_toRemoveHeader != null)
            {
                foreach (var r in _toRemoveHeader)
                {
                    if (myWebHeaderCollection.Get(r) != null)
                    {
                        myWebHeaderCollection.Remove(r);
                    }
                }
            }

            request.Referer = _lasUrl;



            AddCookiesTo(request);               // Add cookies that were saved from previous requests

            if (_isPost)
            {
                AddPostDataTo(request);          // We only need to add post data on a POST request
            }
            return(true);
        }
示例#17
0
        /// <summary>
        /// Event handler for HtmlWeb.PreRequestHandler. Occurs before an HTTP request is executed.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected bool OnPreRequest(HttpWebRequest request)
        {
            request.UserAgent = SettingsManager.GetSessionUserAgent();
            WebHeaderCollection myWebHeaderCollection = request.Headers;

            if (UseCredentials)
            {
                request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
                request.Credentials         = Credentials;
            }
            request.AllowAutoRedirect = this.AutoRedirect;
            myWebHeaderCollection.Add("Accept-Language", SettingsManager.GetSessionAcceptLanguage());
            myWebHeaderCollection.Add("AcceptCharset", SettingsManager.GetSessionAcceptCharset());
            myWebHeaderCollection.Add("TransferEncoding", SettingsManager.GetSessionTransferEncoding());
            myWebHeaderCollection.Add("Connection", SettingsManager.GetConnection());

            if (extraHeader != null)
            {
                foreach (var kv in extraHeader)
                {
                    if (myWebHeaderCollection.Get(kv.Key) == null)
                    {
                        myWebHeaderCollection.Add(kv.Key, kv.Value);
                    }
                }
            }
            if (toRemoveHeader != null)
            {
                foreach (var r in toRemoveHeader)
                {
                    if (myWebHeaderCollection.Get(r) != null)
                    {
                        myWebHeaderCollection.Remove(r);
                    }
                }
            }

            request.Referer = lasUrl;


            AddCookiesTo(request);               // Add cookies that were saved from previous requests

            if (_isPost)
            {
                AddPostDataTo(request);          // We only need to add post data on a POST request
            }
            return(true);
        }
        /// <summary>
        /// 发出一次新的请求,并返回获得的回应
        /// 调用此方法永远不会触发StatusUpdate事件.
        /// </summary>
        /// <returns>相应的HttpWebResponse</returns>
        public HttpWebResponse GetResponse()
        {
            HttpWebRequest req = CreateRequest();

            HttpWebResponse res;

            try
            {
                res = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
            _responseHeaders = res.Headers;

            string cookiestr = _responseHeaders.Get("Set-Cookie");

            if (_keepContext)
            {
                if (_context.Cookies == null)
                {
                    _context.Cookies = new CookieCollection();
                }
                if (!string.IsNullOrEmpty(cookiestr))
                {
                    SetCookie(cookiestr);
                }
                //_context.Cookies = res.Cookies;
                _context.Referer = _url;
            }
            return(res);
        }
示例#19
0
        public void Request(Uri Url, WebHeaderCollection cHeaders, byte[] baPostdata, string sMPBound, int iPostType,
                            string sFilename, bool bReturnStr)
        {
            sResponseCode = ""; msResponse = new MemoryStream();
            URI           = Url; Filename = sFilename; ReturnStr = bReturnStr;
            isReady       = false; State = ReqState.Connecting;
            Headers       = new WebHeaderCollection();
            outHeaders.Add("Host: " + URI.Host);
            outHeaders.Add("Connection: " + "Close");
            outHeaders.Add("User-Agent: pImgDB/" + cb.sAppVer + " (Windows NT 5.1; U; en)");

            for (int a = 0; a < cHeaders.Count; a++)
            {
                outHeaders.Add(cHeaders.GetKey(a) + ": " + cHeaders.Get(a));
            }
            ConMode = iPostType;
            if (ConMode != 1)
            {
                ConQHdr = "POST"; Postdata = baPostdata;
                outHeaders.Add("Content-Length: " + Postdata.Length);
                if (ConMode == 3)
                {
                    MPBound = sMPBound;
                    ConPHdr = "multipart/form-data; boundary=" + MPBound;
                }
                outHeaders.Add("Content-Type: " + ConPHdr);
            }

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerAsync();
        }
示例#20
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);
        }
示例#21
0
 void getCookies(WebHeaderCollection headers)
 {
     string[] accept = new string[] { "rur", "urlgen", "csrftoken" };
     for (int i = 0; i < headers.Count; i++)
     {
         string name = headers.GetKey(i);
         if (name != "Set-Cookie")
         {
             continue;
         }
         string value = headers.Get(i);
         foreach (var singleCookie in value.Split(','))
         {
             Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
             if (match.Captures.Count == 0)
             {
                 continue;
             }
             string cname  = match.Groups[1].ToString();
             string cvalue = match.Groups[2].ToString();
             if (accept.Contains(cname) && !string.IsNullOrEmpty(cvalue))
             {
                 if (cookies.ContainsKey(cname))
                 {
                     cookies[cname] = cvalue;
                 }
                 else
                 {
                     cookies.Add(cname, cvalue);
                 }
             }
         }
     }
 }
示例#22
0
        void ButtongetitOnClick(object obj, EventArgs ea)
        {
            headers.Items.Clear();
            cookies.Items.Clear();
            response.Items.Clear();

            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(uribox.Text);

            hwr.CookieContainer = new CookieContainer();
            HttpWebResponse     hwrsp = (HttpWebResponse)hwr.GetResponse();
            WebHeaderCollection whc   = hwrsp.Headers;

            for (int i = 0; i < whc.Count; i++)
            {
                headers.Items.Add(whc.GetKey(i) + " = " + whc.Get(i));
            }

            hwrsp.Cookies = hwr.CookieContainer.GetCookies(hwr.RequestUri);
            foreach (Cookie cky in hwrsp.Cookies)
            {
                cookies.Items.Add(cky.Name + " = " + cky.Value);
            }

            Stream       strm = hwrsp.GetResponseStream();
            StreamReader sr   = new StreamReader(strm);

            while (sr.Peek() > -1)
            {
                response.Items.Add(sr.ReadLine());
            }
            sr.Close();
            strm.Close();
        }
示例#23
0
        public bool Load(string filename, string URL)
        {
            try
            {
                HttpWebRequest      Myrq      = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                HttpWebResponse     myrp      = (System.Net.HttpWebResponse)Myrq.GetResponse();
                WebHeaderCollection colHeader = myrp.Headers;
                int len = int.Parse(colHeader.Get("Content-Length"));

                Stream st    = myrp.GetResponseStream();
                Stream so    = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                byte[] by    = new byte[1024];
                int    osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                    Console.WriteLine(so.Length);
                }
                so.Close();
                st.Close();
                myrp.Close();
                Myrq.Abort();
                return(true);
            }
            catch (System.Exception e)
            {
                return(false);
            }
        }
示例#24
0
        private IEnumerable <VersionDescription> ParseResponse(WebHeaderCollection header, byte[] body)
        {
            switch (header.Get("Content-Encoding"))
            {
            case "gzip":
                using (var dst = new System.IO.MemoryStream())
                    using (var s = new System.IO.Compression.GZipStream(new System.IO.MemoryStream(body), System.IO.Compression.CompressionMode.Decompress)) {
                        s.CopyTo(dst);
                        dst.Flush();
                        body = dst.ToArray();
                    }
                break;

            case "deflate":
                using (var dst = new System.IO.MemoryStream())
                    using (var s = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(body), System.IO.Compression.CompressionMode.Decompress)) {
                        s.CopyTo(dst);
                        dst.Flush();
                        body = dst.ToArray();
                    }
                break;

            default:
                break;
            }
            return(ParseAppCast(System.Text.Encoding.UTF8.GetString(body)));
        }
示例#25
0
文件: Bai2.cs 项目: ManhKhoa1507/.Net
        private void GetHeader(string url)
        {
            // Get the header
            WebClient myClient = new WebClient();

            byte[] response = myClient.DownloadData(url);
            WebHeaderCollection webHeader = myClient.ResponseHeaders;

            string[] headers = webHeader.AllKeys;

            // Create the listView
            listView1.Items.Clear();
            ListViewItem.ListViewSubItem[] subItems;
            ListViewItem item = null;

            // Display the header to list view
            int i = 0;

            foreach (string s in headers)
            {
                i++;
                item = new ListViewItem(i.ToString());

                subItems = new ListViewItem.ListViewSubItem[]
                {
                    new ListViewItem.ListViewSubItem(item, s),
                    new ListViewItem.ListViewSubItem(item, webHeader.Get(s))
                };

                item.SubItems.AddRange(subItems);
                listView1.Items.Add(item);
            }
        }
        /// <summary>
        /// To the HTTP operation exception.
        /// </summary>
        /// <param name="webException">The web exception.</param>
        /// <param name="httpWebRequest">The HTTP web request.</param>
        /// <param name="cookies">The cookies.</param>
        /// <param name="headers">The headers.</param>
        /// <returns></returns>
        public static HttpOperationException ToHttpOperationException(this WebException webException, HttpWebRequest httpWebRequest, out CookieCollection cookies, out WebHeaderCollection headers)
        {
            HttpOperationException result = null;

            cookies = null;
            headers = null;

            if (webException != null)
            {
                var webResponse = (HttpWebResponse)webException.Response;
                headers = webResponse.Headers;
                var destinationMachine = headers?.Get(HttpConstants.HttpHeader.SERVERNAME);
                cookies = webResponse.Cookies;

                var responseText = webResponse.ReadAsText();

                result = new HttpOperationException(httpWebRequest.RequestUri.ToString(),
                                                    httpWebRequest.Method,
                                                    webException.Message,
                                                    responseText,
                                                    webResponse.StatusCode,
                                                    webException.Status, destinationMachine);
            }

            return(result);
        }
        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;
        }
示例#28
0
        /// <summary>
        /// 设置下载文件名称
        /// </summary>
        /// <param name="savePath"></param>
        /// <param name="webHeaderCollection"></param>
        private void SetDownloadFileName(string savePath, WebHeaderCollection webHeaderCollection)
        {
            token = webHeaderCollection?.Get("ETag")?.Replace("\"", "");//ETag标识作为文件名称
            string fileType = url.Substring(url.LastIndexOf('.'), url.Length - url.LastIndexOf('.'));

            fileName = savePath + @"\" + token + fileType;
        }
示例#29
0
        private void HandlePost(string path, WebHeaderCollection headers, Stream response)
        {
            // TODO maybe handle authorization but I don't really care
            string auth = headers.Get("Authorization");

            HandleGet(path, headers, response);
        }
        public static T GetValue <T>(this WebHeaderCollection webHeaderCollection, string headerName)
        {
            string headerValue = webHeaderCollection.Get(headerName);

            if (string.IsNullOrWhiteSpace(headerValue))
            {
                throw new Exception(string.Format(CultureInfo.InvariantCulture, "Web header '{0}' is not found.", headerName));
            }

            try
            {
                if (typeof(T) == typeof(DateTime))
                {
                    return((T)((object)DateTime.ParseExact(headerValue, "o", CultureInfo.InvariantCulture)));
                }

                if (typeof(T) == typeof(ContentDispositionHeaderValue))
                {
                    return((T)((object)ContentDispositionHeaderValue.Parse(headerValue)));
                }

                if (typeof(T) == typeof(MediaTypeHeaderValue))
                {
                    return((T)((object)MediaTypeHeaderValue.Parse(headerValue)));
                }

                return((T)Convert.ChangeType(headerValue, typeof(T), CultureInfo.InvariantCulture));
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(CultureInfo.InvariantCulture, "Web header '{0}' value '{1}' is invalid", headerName, headerValue), ex);
            }
        }
示例#31
0
    public Hashtable ExecRequest( string Cmd, string ContentType,
                                  string Content, WebHeaderCollection hds,
                                  bool GetResponse )
    {
        byte [] buf;
        string line;

        string req = String.Format(
            "{0} {1} RTSP/1.0\r\n" + "CSeq: {2}\r\n",
            Cmd, url, ++cseq );

        if( session != null )
            req += String.Format( "Session: {0}\r\n", session );

        if( hds != null )
        {
            for( int i = 0; i < hds.Count; i++ )
            {
                req += String.Format( "{0}: {1}\r\n",
                    hds.GetKey( i ), hds.Get( i ) );
            }
        }

        if( ContentType != null && Content != null )
        {
            req += String.Format(
                "Content-Type: {0}\r\n" + "Content-Length: {1}\r\n",
                ContentType, Content.Length );
        }

        req += String.Format( "User-Agent: {0}\r\n", useragent );

        for( int i = 0; i < addheaders.Count; i++ )
        {
            req += String.Format( "{0}: {1}\r\n",
                addheaders.GetKey( i ), addheaders.Get( i ) );
        }

        req += "\r\n";

        if( ContentType != null && Content != null )
            req += Content;

        buf = Encoding.ASCII.GetBytes( req );
        nsctrl.Write( buf, 0, buf.Length );

        if( !GetResponse )
            return null;

        line = srctrl.ReadLine();
        if( line == null || line == "" )
            throw new Exception( "Request failed, read error" );

        string [] tokens = line.Split( new char[] { ' ' } );
        if( tokens.Length != 3 || tokens[ 1 ] != "200" )
            throw new Exception( "Request failed, error " + tokens[ 1 ] );

        string name = null;
        Hashtable ht = new Hashtable();
        while( ( line = srctrl.ReadLine() ) != null && line != "" )
        {
            if( name != null && Char.IsWhiteSpace( line[ 0 ] ) )
            {
                ht[ name ] += line;
                continue;
            }

            int i = line.IndexOf( ":" );
            if( i == -1 )
                throw new Exception( "Request failed, bad header" );

            name = line.Substring( 0, i );
            ht[ name ] = line.Substring( i + 1 ).Trim();
        }

        return ht;
    }
        public void Get_Success()
        {
            string[] keys = { "Accept", "uPgRaDe", "Custom" };
            string[] values = { "text/plain, text/html", " HTTP/2.0 , SHTTP/1.3,  , RTA/x11 ", "\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"" };
            WebHeaderCollection w = new WebHeaderCollection();

            for (int i = 0; i < keys.Length; ++i)
            {
                w.Add(keys[i], values[i]);
            }

            for (int i = 0; i < keys.Length; ++i)
            {
                string expected = values[i].Trim();
                Assert.Equal(expected, w.Get(i));
            }
        }
        public void Get_Fail()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add("Accept", "text/plain");

            Assert.Throws<ArgumentOutOfRangeException>(() => w.Get(-1));
            Assert.Throws<ArgumentOutOfRangeException>(() => w.Get(42));
        }