Beispiel #1
0
        public static string Request(string url, string method, byte[] data, string contentType, bool useProxy = false,
                                     Encoding encoding = null, int timeout = Timeout, NameValueCollection header = null, string userAgent = null,
                                     string referer    = null, CookieContainer cookieContainer = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            HttpWebRequest request = HttpWebRequest.CreateHttp(url);

            request.Method      = method;
            request.ContentType = contentType;
            request.Timeout     = timeout;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }

            if (!string.IsNullOrEmpty(referer))
            {
                request.Referer = referer;
            }

            if (header != null && header.Count > 0)
            {
                request.Headers.Add(header);
            }

            if (useProxy)
            {
                string proxyIP = HttpProxy.GetRandomProxyIP();
                if (proxyIP != "")
                {
                    IWebProxy webProxy = new WebProxy(HttpProxy.GetRandomProxyIP(), 3128);
                    request.Proxy = webProxy;
                }
            }

            if (cookieContainer != null)
            {
                request.CookieContainer = cookieContainer;
            }

            if (method.ToLower() != "get" && data != null)
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                }
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, encoding))
                    {
                        return(reader.ReadToEnd());
                    }
                }
            }
        }