System.Net.HttpWebRequest.GetResponse()

Here are the examples of the csharp api System.Net.HttpWebRequest.GetResponse() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1384 Examples 7

19 Source : SmogonGenner.cs
with MIT License
from architdate

private string GetSmogonPage(string url)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return responseString;
            }
            catch (Exception e)
            {
                WinFormsUtil.Alert("An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: " + e.ToString() + "\nURL tried to access: "+ url);
                return "Error :" + e.ToString();
            }
        }

19 Source : ProductionServerCertificates.cs
with MIT License
from ardalis

[Theory]
        [InlineData("ardalis.com")] // team mentoring site
        [InlineData("devbetter.com")] // individual career mentoring site
        public void MustHaveAtLeast30DaysLeftBeforeExpiring(string domain)
        {
            HttpWebRequest request = WebRequest.CreateHttp($"https://{domain}");
            request.ServerCertificateValidationCallback += ServerCertificateValidationCallback;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
            }
        }

19 Source : Proxy_Back.aspx.cs
with GNU General Public License v3.0
from ardatdev

protected void Page_Load(object sender, EventArgs e)
    {
        string url = Request.QueryString["url"];

        if (url != null)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.Trim());
            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string htmlText = reader.ReadToEnd();
            reader.Close();
            response.Close();
            string a = "href=\"/";
            int link = htmlText.IndexOf(a);
            while (link >= 0)
            {
                htmlText = htmlText.Replace("\"/", "\"" + url);
                if (a.Length < htmlText.Length)
                {
                    link = htmlText.IndexOf(a, a.Length);
                }
                else
                {
                    link = -1;
                }
            }

            Web_Context.Text = htmlText;
        }
    }

19 Source : OutputReaderBase.cs
with GNU General Public License v3.0
from arunsatyarth

public void Read()
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(StatsLink);
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
                request.Accept = "/";
                request.UseDefaultCredentials = true;
                request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                //doc.Save(request.GetRequestStream());
                HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
                Stream stream = resp.GetResponseStream();
                StreamReader sr = new StreamReader(stream);
                string s = sr.ReadToEnd();
                NextLog = s;
            }
            catch (Exception e)
            {
                ReadWithBrowser();
                throw;
            }

        }

19 Source : StaticFilesTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        [InlineData("Microsoft.Owin.Host.HttpListener")]
        public void TooManyRanges_ServeFull(string serverName)
        {
            int port = RunWebServer(
                serverName,
                DefaultStaticFiles);

            // There's a bug in the 4.0 HttpClientHandler for unbounded ('10-') range header values.  Use HWR instead.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:" + port + "/Content/textfile.txt");
            request.AddRange(10);
            request.AddRange(10);
            request.AddRange(10);
            request.AddRange(10);
            request.AddRange(10);
            request.AddRange(10);
            request.AddRange(10);
            request.AddRange(10);
            request.AddRange(10);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
            replacedert.Equal("True", string.Join(",", response.Headers.GetValues("PreplacededThroughOWIN")));
            replacedert.Equal("text/plain", response.ContentType);
        }

19 Source : GitHubAPI.cs
with MIT License
from AstroTechies

public static Version GetLatestVersionFromGitHub(string repo)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetLatestVersionURL(repo));
                request.Method = "GET";
                request.AllowAutoRedirect = false;
                request.ContentType = "application/json; charset=utf-8";
                request.UserAgent = AMLUtils.UserAgent;

                string newURL = null;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    newURL = response.Headers["location"];
                }

                if (string.IsNullOrEmpty(newURL)) return null;
                string[] splitURL = newURL.Split('/');

                string finalVersionBit = splitURL[splitURL.Length - 1];
                if (finalVersionBit[0] == 'v') finalVersionBit = finalVersionBit.Substring(1);

                Version.TryParse(finalVersionBit, out Version foundVersion);
                return foundVersion;
            }
            catch (Exception ex)
            {
                if (ex is WebException || ex is FormatException) return null;
                throw;
            }
        }

19 Source : GitHubAPI.cs
with MIT License
from atenfyr

public static Version GetLatestVersionFromGitHub(string repo)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetLatestVersionURL(repo));
                request.Method = "GET";
                request.AllowAutoRedirect = false;
                request.ContentType = "application/json; charset=utf-8";
                request.UserAgent = "UreplacedetGUI/" + UAGUtils._displayVersion;

                string newURL = null;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    newURL = response.Headers["location"];
                }

                if (string.IsNullOrEmpty(newURL)) return null;
                string[] splitURL = newURL.Split('/');

                string finalVersionBit = splitURL[splitURL.Length - 1];
                if (finalVersionBit[0] == 'v') finalVersionBit = finalVersionBit.Substring(1);
                finalVersionBit = finalVersionBit.Replace(".0-alpha.", ".");

                Version.TryParse(finalVersionBit, out Version foundVersion);
                return foundVersion;
            }
            catch (Exception ex)
            {
                if (ex is WebException || ex is FormatException) return null;
                throw;
            }
        }

19 Source : Loader.cs
with GNU General Public License v3.0
from Athlon007

bool RemoteFileExists(string url)
        {
            try
            {
                //Creating the HttpWebRequest
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "HEAD";
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                string responseUri = response.ResponseUri.ToString();
                response.Close();

                //Returns TRUE if the Status code == 200 and it's not 404.html website
                return (response.StatusCode == HttpStatusCode.OK && responseUri != "http://athlon.kkmr.pl/404.html");
            }
            catch
            {
                return false;
            }
        }

19 Source : AvaTaxClient.cs
with Apache License 2.0
from avadev

private string RestCallString(string verb, AvaTaxPath relativePath, object content = null)
        {
            string path = CombinePath(_envUri.ToString(), relativePath.ToString());
            string jsonPayload = null;
            string mimeType = null;

            // Use HttpWebRequest so we can get a decent response
            var wr = (HttpWebRequest)WebRequest.Create(path);
            wr.Proxy = null;
            wr.Timeout = 1200000;

            // Add headers
            foreach (var key in _clientHeaders.Keys)
            {
                wr.Headers.Add(key, _clientHeaders[key]);
            }

            // Convert the name-value pairs into a byte array
            wr.Method = verb;

            //Upload file.
            if (content != null && content is FileResult) {
                wr.KeepAlive = true;
                var fr = (FileResult)content;
                mimeType = fr.ContentType;
                content = fr.Data;
                string dataBoundary = "----dataBoundary";
                wr.ContentType = "multipart/form-data; boundary=" + dataBoundary;
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + dataBoundary + "\r\n");                
                Stream rs = wr.GetRequestStream();
                rs.Write(boundaryBytes, 0, boundaryBytes.Length);
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string header = string.Format(headerTemplate, fr.Filename, fr.Filename, fr.ContentType);
                byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                rs.Write(headerBytes, 0, headerBytes.Length);
                rs.Write(fr.Data, 0, fr.Data.Length);
                byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + dataBoundary + "--\r\n");
                rs.Write(trailer, 0, trailer.Length);
                rs.Close();
            } else if (content != null) {
                wr.ContentType = mimeType ?? Constants.JSON_MIME_TYPE;
                wr.ServicePoint.Expect100Continue = false;

                // Encode the payload               
                jsonPayload = JsonConvert.SerializeObject(content, SerializerSettings);
                var encoding = new UTF8Encoding();
                byte[] data = encoding.GetBytes(jsonPayload);
                wr.ContentLength = data.Length;

                // Call the server
                using (var s = wr.GetRequestStream()) {
                    s.Write(data, 0, data.Length);
                    s.Close();
                }
            }

            // Transmit, and get back the response, save it to a temp file
            try {
                using (var response = wr.GetResponse()) {
                    using (var inStream = response.GetResponseStream()) {
                        using (var reader = new StreamReader(inStream)) {
                            var responseString = reader.ReadToEnd();

                            // Track the API call
                            var eventargs = new AvaTaxCallEventArgs() { Code = ((HttpWebResponse)response).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = responseString, RequestUri = new Uri(path) };
                            OnCallCompleted(eventargs);

                            // Here's the results
                            return responseString;
                        }
                    }
                }

            // Catch a web exception
            } catch (WebException webex) {
                HttpWebResponse httpWebResponse = webex.Response as HttpWebResponse;
                if (httpWebResponse != null) {
                    using (Stream stream = httpWebResponse.GetResponseStream()) {
                        using (StreamReader reader = new StreamReader(stream)) {
                            var errString = reader.ReadToEnd();

                            // Track the API call
                            var statusCode = ((HttpWebResponse)httpWebResponse).StatusCode;
                            var eventargs = new AvaTaxCallEventArgs() { Code = statusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = errString, RequestUri = new Uri(path) };
                            OnCallCompleted(eventargs);

                            // Here's the results
                            var err = DeserializeErrorResult(errString, statusCode);
                            throw new AvaTaxError(err, httpWebResponse.StatusCode);
                        }
                    }
                }

                // If we can't parse it as an AvaTax error, just throw
                throw webex;
            }
        }

19 Source : AvaTaxClient.cs
with Apache License 2.0
from avadev

private FileResult RestCallFile(string verb, AvaTaxPath relativePath, object content = null)
        {
            string path = CombinePath(_envUri.ToString(), relativePath.ToString());
            string jsonPayload = null;

            // Use HttpWebRequest so we can get a decent response
            var wr = (HttpWebRequest)WebRequest.Create(path);
            wr.Proxy = null;
            wr.Timeout = 1200000;

            // Add headers
            foreach (var key in _clientHeaders.Keys)
            {
                wr.Headers.Add(key, _clientHeaders[key]);
            }

            // Convert the name-value pairs into a byte array
            wr.Method = verb;
            if (content != null) {
                wr.ContentType = Constants.JSON_MIME_TYPE;
                wr.ServicePoint.Expect100Continue = false;

                // Encode the payload
                jsonPayload = JsonConvert.SerializeObject(content, SerializerSettings);
                var encoding = new UTF8Encoding();
                byte[] data = encoding.GetBytes(jsonPayload);
                wr.ContentLength = data.Length;

                // Call the server
                using (var s = wr.GetRequestStream()) {
                    s.Write(data, 0, data.Length);
                    s.Close();
                }
            }

            // Transmit, and get back the response, save it to a temp file
            try {
                using (var response = wr.GetResponse()) {
                    using (var inStream = response.GetResponseStream()) {
                        const int BUFFER_SIZE = 1024;
                        var chunks = new List<byte>();
                        var totalBytes = 0; 
                        var bytesRead = 0;

                        do
                        {
                            var buffer = new byte[BUFFER_SIZE];
                            bytesRead = inStream.Read(buffer, 0, BUFFER_SIZE);
                            if (bytesRead == BUFFER_SIZE) {
                                chunks.AddRange(buffer);
                            } else {
                                for (int i = 0; i < bytesRead; i++) {
                                    chunks.Add(buffer[i]);
                                }
                            }
                            totalBytes += bytesRead;
                        } while (bytesRead > 0);
        
                        if(totalBytes <= 0) {
                            throw new IOException("Response contained no data");
                        }

                        // Here's your file result
                        var fr = new FileResult()
                        {
                            ContentType = response.Headers["Content-Type"].ToString(),
                            Filename = GetDispositionFilename(response.Headers["Content-Disposition"].ToString()),
                            Data = chunks.ToArray()
                        };

                        // Track the API call
                        var eventargs = new AvaTaxCallEventArgs() { Code = ((HttpWebResponse)response).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseBody = fr.Data, RequestUri = new Uri(path) };
                        OnCallCompleted(eventargs);
                        return fr;
                    }
                }

                // Catch a web exception
            } catch (WebException webex) {
                HttpWebResponse httpWebResponse = webex.Response as HttpWebResponse;
                if (httpWebResponse != null) {
                    using (Stream stream = httpWebResponse.GetResponseStream()) {
                        using (StreamReader reader = new StreamReader(stream)) {
                            var errString = reader.ReadToEnd();

                            // Track the API call
                            var statusCode = ((HttpWebResponse)httpWebResponse).StatusCode;
                            var eventargs = new AvaTaxCallEventArgs() { Code = statusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = errString, RequestUri = new Uri(path) };
                            OnCallCompleted(eventargs);

                            // Preplaced on the error
                            var err = DeserializeErrorResult(errString, statusCode);
                            throw new AvaTaxError(err, httpWebResponse.StatusCode);
                        }
                    }
                }

                // If we can't parse it as an AvaTax error, just throw
                throw webex;
            }
        }

19 Source : ApiWrapper.cs
with MIT License
from Avanade

public override T Get<T>(string serviceRoute, [Optional] Dictionary<string, string> header)
        {
            serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");

            ///Calls the service following the route 
            HttpWebRequest request = null;
            dynamic response = null;

            ///Building the Request
            request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
            request.Method = "GET";
            request.ContentType = "application/json; encoding='utf-8'";

            ///Sends the authentication token if exisists, 
            if (!String.IsNullOrEmpty(_token))
                request.Headers.Add("Authorization", _token);

            if (header != null)
                foreach (var item in header)
                {
                    request.Headers.Add(item.Key, item.Value);
                }

            ///Gets the Response from API
            response = (HttpWebResponse)request.GetResponse();
            if (typeof(T) == typeof(HttpWebResponse))
            {
                return response;
            }
            else
            {
                ///Converts te Response in text to return
                string responseText;
                using (var reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseText = reader.ReadToEnd();
                }

                ///Now load the JSON Doreplacedent
                return JToken.Parse(responseText).ToObject<T>();
            }
        }

19 Source : ApiWrapper.cs
with MIT License
from Avanade

public override DomainResponse Delete(string serviceRoute, [Optional]Dictionary<string, string> headers)
        {
            serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty)
                                        .Replace("\"", "'");
            ///Calls the service following the route  
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
            request.Method = "DELETE";
            request.ContentType = "application/json";

            ///Send the authentication token if exisists
            if (!String.IsNullOrEmpty(_token))
                request.Headers.Add("Authorization", _token);

            ///Get the Response
            response = (HttpWebResponse)request.GetResponse();
            string responseText;
            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                responseText = reader.ReadToEnd();
            }

            ///return new DomainResponse(true, responseText);
            return new DomainResponse()
            {
                PayLoad = responseText
            };
        }

19 Source : ApiWrapper.cs
with MIT License
from Avanade

public override JToken Get(string serviceRoute, [Optional] Dictionary<string, string> header)
        {
            serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");

            ///Calls the service following the route  
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
            request.Method = "GET";
            request.ContentType = "application/json; encoding='utf-8'";

            ///Sends the authorization token if exisists
            if (!String.IsNullOrEmpty(_token))
                request.Headers.Add("Authorization", _token);

            if (header != null)
                foreach (var item in header)
                {
                    request.Headers.Add(item.Key, item.Value);
                }

            ///Get the Response from the API
            response = (HttpWebResponse)request.GetResponse();

            ///Converts te Response in text to return
            string responseText;
            using (var reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                responseText = reader.ReadToEnd();
            }

            ///Now load the JSON Doreplacedent
            return JToken.Parse(responseText);
        }

19 Source : ApiWrapper.cs
with MIT License
from Avanade

public override T Delete<T>(string serviceRoute, [Optional]Dictionary<string, string> headers)
        {
            serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");

            //Calls the service following the route 
            HttpWebRequest request = null;
            dynamic response = null;

            request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
            request.Method = "DELETE";
            request.ContentType = "application/json";

            ///Send the authentication token if exisists
            if (!String.IsNullOrEmpty(_token))
                request.Headers.Add("Authorization", _token);
             
            if (headers != null)
                foreach (var item in headers)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            ///Get the Response
            response = (HttpWebResponse)request.GetResponse();

            if (typeof(T) == typeof(HttpWebResponse))
            {
                return response;
            }
            else
            {
                string responseText;
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseText = reader.ReadToEnd();
                }

                ///return new DomainResponse;
                return JToken.Parse(responseText).ToObject<T>();
            }
        }

19 Source : App.cs
with GNU General Public License v3.0
from Avinch

public static string GetAppName(int id)
        {

            string appName = "Unknown App";

            string requestUrl = string.Format(CultureInfo.InvariantCulture,
                "https://store.steampowered.com/api/appdetails?appids={0}", id);

            var requestContents = string.Empty;

            const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
            const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
            ServicePointManager.SecurityProtocol = Tls12;

            var webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
            webRequest.Method = "GET";
            WebResponse response = null;

            try
            {
                response = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (System.Net.WebException ex)
            {
                Logger.Instance.Error("Failed to retrieve app name, defaulting to Unknown App");
                Logger.Instance.Exception(ex);
                return appName;
            }

            using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
            {
                requestContents = streamReader.ReadToEnd();
            }

            try
            {
                dynamic jsonContents = JObject.Parse(requestContents);
                appName = jsonContents[id.ToString()]["data"]["name"];
            }
            catch (JsonReaderException jsonEx)
            {
                Logger.Instance.Error("Failed to read app name");
                Logger.Instance.Exception(jsonEx);
            }
            catch (Exception ex)
            {
                Logger.Instance.Exception(ex);
            }

            return appName;
        }

19 Source : BaiduApiHelper.cs
with MIT License
from awesomedotnetcore

public string RequestData(string method,string host, string url, Dictionary<string, object> paramters=null)
        {
            string ak = _accessKeyId;
            string sk = _secretAccessKey;
            DateTime now = DateTime.Now.ToCstTime();
            int expirationInSeconds = 1200;

            HttpWebRequest req = WebRequest.Create(host + url) as HttpWebRequest;
            Uri uri = req.RequestUri;
            req.Method = method;
            req.ContentType = "application/json";

            if (paramters != null)
            {
                Stream requestStream = req.GetRequestStream();
                byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(paramters));
                requestStream.Write(data, 0, data.Length);
            }

            string signDate = now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssK");
            string authString = "bce-auth-v1/" + ak + "/" + signDate + "/" + expirationInSeconds;
            string signingKey = Hex(new HMACSHA256(Encoding.UTF8.GetBytes(sk)).ComputeHash(Encoding.UTF8.GetBytes(authString)));

            string canonicalRequestString = CanonicalRequest(req);

            string signature = Hex(new HMACSHA256(Encoding.UTF8.GetBytes(signingKey)).ComputeHash(Encoding.UTF8.GetBytes(canonicalRequestString)));
            string authorization = authString + "/host/" + signature;

            req.Headers.Add("x-bce-date", signDate);
            req.Headers.Add(HttpRequestHeader.Authorization, authorization);

            HttpWebResponse res;
            string message = "";
            try
            {
                res = req.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                res = e.Response as HttpWebResponse;
            }
            message = new StreamReader(res.GetResponseStream()).ReadToEnd();

            return message;
        }

19 Source : HttpHelper.cs
with MIT License
from awesomedotnetcore

public static string RequestData(string method, string url, string body, string contentType, Dictionary<string, string> headers = null, X509Certificate cerFile = null)
        {
            if (string.IsNullOrEmpty(url))
                throw new Exception("请求地址不能为NULL或空!");

            string newUrl = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newUrl);
            request.Method = method.ToUpper();
            request.ContentType = contentType;
            headers?.ForEach(aHeader =>
            {
                request.Headers.Add(aHeader.Key, aHeader.Value);
            });

            //HTTPS证书
            if (cerFile != null)
                request.ClientCertificates.Add(cerFile);

            if (method.ToUpper() != "GET")
            {
                byte[] data = Encoding.UTF8.GetBytes(body);
                request.ContentLength = data.Length;

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                }
            }

            string resData = string.Empty;
            DateTime startTime = DateTime.Now;
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    int httpStatusCode = (int)response.StatusCode;
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        resData = reader.ReadToEnd();

                        return resData;
                    }
                }
            }
            catch (Exception ex)
            {
                resData = $"异常:{ExceptionHelper.GetExceptionAllMsg(ex)}";

                throw ex;
            }
            finally
            {
                var time = DateTime.Now - startTime;
                if (resData?.Length > 1000)
                {
                    resData = new string(resData.Copy(0, 1000).ToArray());
                    resData += "......";
                }

                string log =
$@"方向:请求外部接口
url:{url}
method:{method}
contentType:{contentType}
body:{body}
耗时:{(int)time.TotalMilliseconds}ms

返回:{resData}
";
                HandleLog?.Invoke(log);
            }
        }

19 Source : HttpHelper.cs
with MIT License
from awesomedotnetcore

public static string GetHtml(string url)
        {
            string htmlCode;
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                    webRequest.Timeout = 10000;
                    webRequest.Method = "GET";
                    webRequest.UserAgent = "Mozilla/4.0";
                    webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");

                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    //获取目标网站的编码格式
                    string contentype = webResponse.Headers["Content-Type"];
                    Regex regex = new Regex("charset\\s*=\\s*[\\W]?\\s*([\\w-]+)", RegexOptions.IgnoreCase);
                    //如果使用了GZip则先解压
                    if (webResponse.ContentEncoding.ToLower() == "gzip")
                    {
                        Stream streamReceive = webResponse.GetResponseStream();
                        MemoryStream ms = new MemoryStream();
                        streamReceive.CopyTo(ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        var zipStream = new GZipStream(ms, CompressionMode.Decompress);
                        //匹配编码格式
                        if (regex.IsMatch(contentype))
                        {
                            Encoding ending = Encoding.GetEncoding(regex.Match(contentype).Groups[1].Value.Trim());
                            using (StreamReader sr = new StreamReader(zipStream, ending))
                            {
                                htmlCode = sr.ReadToEnd();
                            }
                        }
                        else//匹配不到则自动转换成utf-8
                        {
                            StreamReader sr = new StreamReader(zipStream, Encoding.GetEncoding("utf-8"));

                            htmlCode = sr.ReadToEnd();
                            string subStr = htmlCode.Substring(0, 2000);
                            string pattern = "charset=(.*?)\"";
                            Encoding encoding;
                            foreach (Match match in Regex.Matches(subStr, pattern))
                            {
                                if (match.Groups[1].ToString().ToLower() == "utf-8")
                                    break;
                                else
                                {
                                    encoding = Encoding.GetEncoding(match.Groups[1].ToString().ToLower());
                                    ms.Seek(0, SeekOrigin.Begin);//设置流的初始位置
                                    var zipStream2 = new GZipStream(ms, CompressionMode.Decompress);
                                    StreamReader sr2 = new StreamReader(zipStream2, encoding);
                                    htmlCode = sr2.ReadToEnd();
                                }
                            }
                        }
                    }
                    else
                    {
                        using (Stream streamReceive = webResponse.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(streamReceive, Encoding.Default))
                            {
                                htmlCode = sr.ReadToEnd();
                            }
                        }
                    }
                    return htmlCode;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Console.WriteLine("重试中....................");
                }
            }

            return "";
        }

19 Source : HttpOutDiagnosticListenerTest.cs
with Apache License 2.0
from aws

[TestMethod]
        public void TestHttpWebRequestSend()
        {
            AWSXRayRecorder.Instance.BeginSegment("HttpWebRequestSegment", TraceId);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            using (var response = request.GetResponse()) { }

            var segment = AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();
            AWSXRayRecorder.Instance.EndSegment();

            // HttpOutDiagnosticListenerNetstandard injects trace header in HttpRequestMessage layer, upon which 
            // HttpWebRequest layer is built, and trace header will be preplaceded to downstream service through HttpRequestMessage,
            // but will not be present in HttpWebRequest header.
#if NET45
            replacedert.IsNotNull(request.Headers[TraceHeader.HeaderKey]);
#endif

            var requestInfo = segment.Subsegments[0].Http["request"] as Dictionary<string, object>;
            replacedert.AreEqual(URL, requestInfo["url"]);
            replacedert.AreEqual("GET", requestInfo["method"]);

            var responseInfo = segment.Subsegments[0].Http["response"] as Dictionary<string, object>;
            replacedert.AreEqual(200, responseInfo["status"]);
            replacedert.IsNotNull(responseInfo["content_length"]);
        }

19 Source : HttpOutDiagnosticListenerTest.cs
with Apache License 2.0
from aws

[TestMethod]
        public void TestHttpWebRequestSend404()
        {
            AWSXRayRecorder.Instance.BeginSegment("HttpWebRequestSegment", TraceId);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL404);
            try
            {
                using (var response = request.GetResponse())
                {
                }
                replacedert.Fail();
            }
            catch (WebException) // Expected
            {
                var segment = AWSXRayRecorder.Instance.TraceContext.GetEnreplacedy();
                AWSXRayRecorder.Instance.EndSegment();

                // HttpOutDiagnosticListenerNetstandard injects trace header in HttpRequestMessage layer, upon which 
                // HttpWebRequest layer is built, and trace header will be preplaceded to downstream service through HttpRequestMessage,
                // but will not be present in HttpWebRequest header.
#if NET45
                replacedert.IsNotNull(request.Headers[TraceHeader.HeaderKey]);
#endif

                var requestInfo = segment.Subsegments[0].Http["request"] as Dictionary<string, object>;
                replacedert.AreEqual(URL404, requestInfo["url"]);
                replacedert.AreEqual("GET", requestInfo["method"]);

                var subsegment = segment.Subsegments[0];
                replacedert.IsTrue(subsegment.HasError);
                replacedert.IsFalse(subsegment.HasFault);
            }
        }

19 Source : HttpHelpers.cs
with Apache License 2.0
from aws-samples

public static HttpWebResponse GetResponse(HttpWebRequest request)
        {
            // Get the response and read any body into a string, then display.
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Logger.LogDebug("\n-- HTTP call succeeded");
                    var responseBody = ReadResponseBody(response);
                    if (!string.IsNullOrEmpty(responseBody))
                    {
                        Logger.LogDebug("\n-- Response body:");
                        Logger.LogDebug(responseBody);     
                    }
                }
                else
                    Logger.LogDebug($"\n-- HTTP call failed, status code: {response.StatusCode}");

                return response;
            }
        }

19 Source : HttpHelpers.cs
with Apache License 2.0
from aws-samples

public static HttpWebResponse GetResponse(HttpWebRequest request)
        {
            // Get the response and read any body into a string, then display.
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Logger.LogDebug("\n-- HTTP call succeeded");
                    var responseBody = ReadResponseBody(response);
                    if (!string.IsNullOrEmpty(responseBody))
                    {
                        Logger.LogDebug("\n-- Response body:");
                        Logger.LogDebug(responseBody);
                    }
                }
                else
                    Logger.LogDebug($"\n-- HTTP call failed, status code: {response.StatusCode}");

                return response;
            }
        }

19 Source : AyFuncHttp.cs
with MIT License
from ay2015

public  string PostData(string url, string postData)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            reader.Close();
            return content;
        }

19 Source : AyFuncHttp.cs
with MIT License
from ay2015

public string PostData<T>(string url, T model, string filter = "")
        {
            string postData = BuildPostData<T>(model, filter);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            reader.Close();
            return content;
        }

19 Source : AyFuncHttp.cs
with MIT License
from ay2015

public string PostDataPartial<T>(string url, T model, string condition = "")
        {
            string postData = BuildPostDataPartial<T>(model, condition);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            reader.Close();
            return content;
        }

19 Source : AyFuncHttp.cs
with MIT License
from ay2015

public string DoGet(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildPostData(parameters);
                }
                else
                {
                    url = url + "?" + BuildPostData(parameters);
                }
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = "GET";
            req.KeepAlive = true;
            req.UserAgent = "Test";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            HttpWebResponse rsp = null;
            try
            {
                rsp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException webEx)
            {
                if (webEx.Status == WebExceptionStatus.Timeout)
                {
                    rsp = null;
                }
            }

            if (rsp != null)
            {
                if (rsp.CharacterSet != null)
                {
                    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    return GetResponsereplacedtring(rsp, encoding);
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }

19 Source : AyAddress.cs
with MIT License
from ay2015

private static string GetBaiDuMapApiResult(string tag,int count)
        {
            string html = string.Empty;
            string ak = "MLrSlgdxGi6DD9k8VfI4CNQ5vhYIzc7g"; //目前由个人账号申请,每天可调2000次,使用时请注意换掉
            string url = string.Format("http://api.map.baidu.com/place/v2/search?q={0}®ion={1}&output=json&ak={2}&page_num={3}&page_size={4}",
                GetQueryStrRandom(),
                tag, ak, RandomNum(0, 400/count), //每次默认会搜出400条记录
                count);
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";

                Encoding encoding = Encoding.UTF8;//根据网站的编码自定义    
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();

                StreamReader streamReader = new StreamReader(responseStream, encoding);
                string retString = streamReader.ReadToEnd();

                streamReader.Close();
                responseStream.Close();

                return retString;
            }
            catch (WebException ex)
            {
                throw new Exception(ex.Message);
            }
        }

19 Source : API.cs
with MIT License
from AyrA

public static byte[] Preview(Guid MapId)
        {
            if (MapId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(MapId));
            }
            var Request = WebRequest.CreateHttp(API_PREVIEW.Replace(API_MAP_ID_PLACEHOLDER, MapId.ToString()));
            try
            {
                using (var Res = Request.GetResponse())
                {
                    using (var MS = new MemoryStream())
                    {
                        using (var S = Res.GetResponseStream())
                        {
                            S.CopyTo(MS);
                        }
                        return MS.ToArray();
                    }
                }
            }
            catch
            {
                return null;
            }
        }

19 Source : API.cs
with MIT License
from AyrA

public static bool Download(Guid MapId, Stream Output)
        {
            if (Output == null)
            {
                throw new ArgumentNullException(nameof(Output));
            }
            if (MapId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(MapId));
            }
            if (!Output.CanWrite)
            {
                throw new ArgumentException("Stream is not writable", nameof(Output));
            }
            var Request = WebRequest.CreateHttp(API_DOWNLOAD.Replace(API_MAP_ID_PLACEHOLDER, MapId.ToString()));
            //Automatically decompress the data. If not available in your language, use regular gzip decompression.
            Request.AutomaticDecompression = DecompressionMethods.GZip;

            try
            {
                using (var Res = Request.GetResponse())
                {
                    using (var S = Res.GetResponseStream())
                    {
                        S.CopyTo(Output);
                    }
                }
            }
            catch (Exception ex)
            {
                SatisfactorySaveEditor.Log.Write("API: Unable to download the map");
                SatisfactorySaveEditor.Log.Write(ex);
                return false;
            }
            return true;
        }

19 Source : UpdateHandler.cs
with MIT License
from AyrA

public static bool DownloadUpdate(string FileName = null)
        {
            if (!ObtainUpdateInfo())
            {
                Log.Write("DownloadUpdate failed: ObtainUpdateInfo not successful");
                return false;
            }
            //Generate file name
            if (string.IsNullOrEmpty(FileName))
            {
                return DownloadUpdate(DefaultUpdateExecutable);

            }
            FileStream FS = null;
            try
            {
                FS = File.Create(FileName);
            }
            catch (Exception ex)
            {
                Log.Write(new Exception($"Unable to write new executable to {FileName}", ex));
                return false;
            }
            using (FS)
            {
                //Don't bother the API in debug mode
                if (Program.DEBUG)
                {
                    Log.Write("Faking download in Debug mode by copying current executable instead.");
                    using (var IN = File.OpenRead(CurrentExecutable))
                    {
                        IN.CopyTo(FS);
                        return true;
                    }
                }
                var Req = GetReq(UpdateData.DownloadURL.ToString());

                HttpWebResponse Res;
                try
                {
                    Res = (HttpWebResponse)Req.GetResponse();
                }
                catch (Exception ex)
                {
                    Log.Write(new Exception("Unable to make executable download request", ex));
                    //Unable to make request at this time
                    return false;
                }
                using (Res)
                {
                    using (var S = Res.GetResponseStream())
                    {
                        S.CopyTo(FS);
                    }
                }
                Log.Write("Update ready at {0}", FileName);
                return true;
            }
        }

19 Source : Program.cs
with MIT License
from AyrA

private static MakeMKV GetKey()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpWebRequest WReq = WebRequest.CreateHttp("https://cable.ayra.ch/makemkv/api.php?xml");
            WebResponse WRes;
            //If you modify the tool, please add some personal twist to the user agent string
            WReq.UserAgent = string.Format("AyrA/MakeMKVUpdater-{0} ({1}/{2};{3}) +https://github.com/AyrA/MakeMKV",
                Settings.GetVersion(),
                Environment.OSVersion.Platform,
                Environment.OSVersion.Version,
                Environment.OSVersion.VersionString);
            try
            {
                WRes = WReq.GetResponse();
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.Print(ex.Message);
                return default(MakeMKV);
            }
            using (WRes)
            {
                using (var S = WRes.GetResponseStream())
                {
                    using (var SR = new StreamReader(S))
                    {
                        var Ser = new XmlSerializer(typeof(MakeMKV));
                        try
                        {
                            return (MakeMKV)Ser.Deserialize(SR);
                        }
                        catch
                        {
                            return default(MakeMKV);
                        }
                    }
                }
            }
        }

19 Source : FeatureReport.cs
with MIT License
from AyrA

public static void Report()
        {
            //Don't bother reporting if it doesn't works
            if (Id == Guid.Empty)
            {
                Log.Write("{0}: Reporting Failed. ID not set", nameof(FeatureReport));
                return;
            }
            //Prevent multiple reports from stacking up
            lock (UsedFeatures)
            {
                //Don't bother reporting if nothing is there to report
                if (UsedFeatures.Count > 0)
                {
                    var BaseFields = new string[] {
                    $"id={Id}",
                    $"version={Tools.CurrentVersion}"
                };
                    WebResponse Res = null;
                    var Req = WebRequest.CreateHttp(REPORT_URL);
                    Req.UserAgent = UpdateHandler.UserAgent;
                    Req.Method = "POST";
                    Req.ContentType = "application/x-www-form-urlencoded";
                    try
                    {
                        var Features = Encoding.UTF8.GetBytes(string.Join("&", UsedFeatures.Distinct().Select(m => $"feature[]={m}").Concat(BaseFields)));
                        Req.ContentLength = Features.Length;
                        using (var S = Req.GetRequestStream())
                        {
                            S.Write(Features, 0, Features.Length);
                            S.Close();
                        }
                        Res = Req.GetResponse();
                    }
                    catch (WebException ex)
                    {
                        try
                        {
                            using (Res = ex.Response)
                            {
                                using (var SR = new StreamReader(Res.GetResponseStream()))
                                {
#if DEBUG
                                    Tools.E(SR.ReadToEnd(), "DEBUG Report Error");
#else
                                    Log.Write("{0}: Reporting failed. Data: {1}", nameof(FeatureReport), SR.ReadToEnd());
#endif
                                }
                            }
                        }
                        catch
                        {
                            Log.Write("{0}: Reporting failed (unable to provide a reason, response is null)", nameof(FeatureReport));
                        }
                        return;
                    }
                    catch (Exception ex)
                    {
                        Log.Write("{0}: Reporting failed (unable to provide a reason, not a WebException)", nameof(FeatureReport));
                        Log.Write(ex);
                    }
                    //Report OK. Clear list and log message
                    UsedFeatures.Clear();
                    using (Res)
                    {
                        using (var SR = new StreamReader(Res.GetResponseStream()))
                        {
                            Log.Write("{0}: Reporting OK. Data: {1}", nameof(FeatureReport), SR.ReadToEnd());
                        }
                    }
                }
            }
        }

19 Source : UpdateHandler.cs
with MIT License
from AyrA

public static bool ObtainUpdateInfo()
        {
            if (!InfoReady)
            {
                var Req = GetReq(UPDATE_URL);

                HttpWebResponse Res;
                try
                {
                    Res = (HttpWebResponse)Req.GetResponse();
                }
                catch (Exception ex)
                {
                    Log.Write(new Exception("Unable to make update request", ex));
                    //Unable to make request at this time
                    return false;
                }
                using (Res)
                {
                    using (var SR = new StreamReader(Res.GetResponseStream()))
                    {
                        try
                        {
                            //Make sure the version string is always parsed with 4 segments (W.X.Y.Z)
                            var V = string.Join(".", (SR.ReadLine() + ".0.0.0")
                                .Substring(1)
                                .Split('.')
                                .Take(4));
                            UpdateData = new UpdateInfo()
                            {
                                NewVersion = new Version(V),
                                DownloadURL = new Uri(SR.ReadLine())
                            };
                            InfoReady = true;
                            return true;
                        }
                        catch (Exception ex)
                        {
                            Log.Write(new Exception("Unable to parse update status response", ex));
                            //Invalid return values
                            return false;
                        }
                    }
                }
            }
            Log.Write("ObtainUpdateInfo already performed");
            return true;
        }

19 Source : GoogleOAuth2Provider.cs
with Apache License 2.0
from azanov

public static GoogleAccessToken GetAccessToken(string code)
        {
            string postData = string.Format("client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}&redirect_uri={3}", CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI);


            HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create(GET_ACCESS_TOKEN_URI); request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";

            
            byte[] postBytes = Encoding.UTF8.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using(var responseReader = new StreamReader(response.GetResponseStream()))
            {
                var tmp = responseReader.ReadToEnd();
                return JsonHelper.From<GoogleAccessToken>(tmp);
            }
        }

19 Source : OutlookOAuth2Provider.cs
with Apache License 2.0
from azanov

public static OutlookAccessToken GetAccessToken(string code)
        {
            string postData = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code", CLIENT_ID, REDIRECT_URI, CLIENT_SECRET, code);


            HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create(GET_ACCESS_TOKEN_URI); request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";


            byte[] postBytes = Encoding.UTF8.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (var responseReader = new StreamReader(response.GetResponseStream()))
            {
                var tmp = responseReader.ReadToEnd();
                return JsonHelper.From<OutlookAccessToken>(tmp);
            }
        }

19 Source : YahooOAuth2Provider.cs
with Apache License 2.0
from azanov

public static YahooAccessToken GetAccessToken(string code)
        {
            string postData = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code", CLIENT_ID, REDIRECT_URI, CLIENT_SECRET, code);


            HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create(GET_ACCESS_TOKEN_URI); request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(CLIENT_ID + ":" + CLIENT_SECRET)));

            byte[] postBytes = Encoding.UTF8.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (var responseReader = new StreamReader(response.GetResponseStream()))
            {
                var tmp = responseReader.ReadToEnd();
                return JsonHelper.From<YahooAccessToken>(tmp);
            }
        }

19 Source : WebDAV.cs
with MIT License
from azist

private static List<Version> doListVersions(string rootURL, string uName, string uPwd,
        string startVersion = "1", string endVersion = null, int? limit = null)
      {
        var sb = new StringBuilder();

        sb.AppendLine("<?xml version=\"1.0\"?>");
        sb.AppendLine("<S:log-report xmlns:S=\"svn:\">");

        sb.AppendLine("<S:start-revision>{0}</S:start-revision>".Args(startVersion));

        if (endVersion.IsNotNullOrWhiteSpace())
          sb.AppendLine("<S:end-revision>{0}</S:end-revision>".Args(endVersion));

        if (limit.HasValue)
          sb.AppendLine("<S:limit>{0}</S:limit>".Args(limit.Value));

        sb.AppendLine("<S:date/>");
        sb.AppendLine("</S:log-report>");

        byte[] contentBytes = Encoding.UTF8.GetBytes(sb.ToString());

        Uri uri = new Uri(rootURL);

        HttpWebRequest request = makeRequest(uri, uName, uPwd, 0, REPORT_METHOD);

        request.Headers.Set("Depth", "0");

        request.ContentLength = contentBytes.Length;
        request.ContentType = "text/xml";

        using (var requestStream = request.GetRequestStream())
          requestStream.Write(contentBytes, 0, contentBytes.Length);

        using (var response = (HttpWebResponse)request.GetResponse())
        {
          if (response.StatusCode == HttpStatusCode.OK)
          {
            using (Stream responseStream = response.GetResponseStream())
            {
              using (StreamReader responseReader = new StreamReader(responseStream))
              {
                string responseStr = responseReader.ReadToEnd();
                IEnumerable<Version> items = createVersionsFromXML(responseStr);

                return items.ToList();
              }
            }
          }
          else
            throw new AzosIOException(Azos.Web.StringConsts.HTTP_OPERATION_ERROR + typeof(WebDAV).Name +
              ".listVersions: response.StatusCode=\"{0}\"".Args(response.StatusCode));
        }
      }

19 Source : WebDAV.cs
with MIT License
from azist

internal List<Item> listDirectoryContent(Directory dir = null, int depth = 1)
      {
        string relativeUrl = dir != null ? dir.Path : string.Empty;
        Uri uri = new Uri(vercificatePathIfNeeded(m_RootUri.AbsoluteUri.TrimEnd('/') + "/" + relativeUrl.Trim('/')));

        log(uri.ToString(), "listDirectoryContent(dir='{0}',depth='{1}')".Args(dir, depth));

        HttpWebRequest request = makeRequest(uri, LIST_CONTENT_METHOD);

        request.Headers.Set("Depth", "1");

        request.ContentLength = LIST_CONTENT_BODY_BYTES.Length;
        request.ContentType = "text/xml";

        using (Stream requestStream = request.GetRequestStream())
          requestStream.Write(LIST_CONTENT_BODY_BYTES, 0, LIST_CONTENT_BODY_BYTES.Length);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
          if ((int)response.StatusCode == HTTP_STATUS_CODE_MULTISTATUS)
          {
            using (Stream responseStream = response.GetResponseStream())
            {
              using (StreamReader responseReader = new StreamReader(responseStream))
              {
                string responseStr = responseReader.ReadToEnd();
                IEnumerable<Item> items = createItemsFromXML(responseStr, dir);
                if (depth != 0)
                  items = items.Skip(1);

                return items.ToList();
              }
            }
          }
          else
            throw new AzosIOException(Azos.Web.StringConsts.HTTP_OPERATION_ERROR + this.GetType().Name +
              ".getFileContent: response.StatusCode=\"{0}\"".Args(response.StatusCode));
        }
      }

19 Source : WebDAV.cs
with MIT License
from azist

internal void getFileContent(File file, Stream stream)
      {
        Uri uri = new Uri(vercificatePathIfNeeded(m_RootUri.AbsoluteUri.TrimEnd('/') + "/" + file.Path.Trim('/')));

        log(uri.ToString(), "getFileContent()");

        HttpWebRequest request = makeRequest(uri);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
          if (response.StatusCode == HttpStatusCode.OK)
          {
            using (Stream responseStream = response.GetResponseStream())
            {
              responseStream.CopyTo(stream);
            }
          }
          else
            throw new AzosIOException(Azos.Web.StringConsts.HTTP_OPERATION_ERROR + this.GetType().Name +
              "getFileContent: response.StatusCode=\"{0}\"".Args(response.StatusCode));
        }
      }

19 Source : WaveTest.cs
with MIT License
from azist

[Run]
        public void MultipartEncoding()
        {
          var encoding = Encoding.GetEncoding("ISO-8859-1");

          var part = new Azos.Web.Multipart.Part("field");
          part.Content = "Value";

          var mp = new Azos.Web.Multipart(new Azos.Web.Multipart.Part[] { part });
          var enc = mp.Encode(encoding);

          var req = HttpWebRequest.CreateHttp(INTEGRATION_HTTP_ADDR + "MultipartEncoding");
          req.Method = "POST";
          req.ContentType = Azos.Web.ContentType.FORM_MULTIPART_ENCODED + "; charset=iso-8859-1";
          req.ContentLength = enc.Length;
          req.CookieContainer = new CookieContainer();
          req.CookieContainer.Add(S_WAVE_URI, S_WAVE_COOKIE);

          using (var reqs = req.GetRequestStream())
          {
            reqs.Write(enc.Buffer, 0, (int)enc.Length);
            var resp = req.GetResponse();

            var ms = new MemoryStream();
            resp.GetResponseStream().CopyTo(ms);

            Aver.AreEqual(part.Content.replacedtring(), encoding.GetString(ms.ToArray()));
          }
        }

19 Source : WaveTest.cs
with MIT License
from azist

private void MultipartTest(string type)
        {
          var partField = new Azos.Web.Multipart.Part("field");
          partField.Content = "value";

          var partTxtFile = new Azos.Web.Multipart.Part("text");
          partTxtFile.Content = "Text with\r\nnewline";
          partTxtFile.FileName = "TxtFile";
          partTxtFile.ContentType = "Content-type: text/plain";

          var partBinFile = new Azos.Web.Multipart.Part("bin");
          partBinFile.Content = new byte[] { 0xff, 0xaa, 0x89, 0xde, 0x23, 0x20, 0xff, 0xfe, 0x02 };
          partBinFile.FileName = "BinFile";
          partBinFile.ContentType = "application/octet-stream";

          var mp = new Azos.Web.Multipart(new Azos.Web.Multipart.Part[] { partField, partTxtFile, partBinFile });

          var enc = mp.Encode();

          var req = HttpWebRequest.CreateHttp(INTEGRATION_HTTP_ADDR + type);
          req.Method = "POST";
          req.ContentType = Azos.Web.ContentType.FORM_MULTIPART_ENCODED;
          req.ContentLength = enc.Length;
          req.CookieContainer = new CookieContainer();
          req.CookieContainer.Add(S_WAVE_URI, S_WAVE_COOKIE);

          using (var reqs = req.GetRequestStream())
          {
            reqs.Write(enc.Buffer, 0, (int)enc.Length);
            var resp = req.GetResponse();

            var ms = new MemoryStream();
            resp.GetResponseStream().CopyTo(ms);
            var returned = ms.ToArray();

            var fieldSize = Encoding.UTF8.GetBytes(partField.Content.replacedtring()).Length;
            var txtFileSize = Encoding.UTF8.GetBytes(partTxtFile.Content.replacedtring()).Length;
            Aver.AreEqual(partField.Content.replacedtring(), Encoding.UTF8.GetString(returned.Take(fieldSize).ToArray()));
            Aver.AreEqual(partTxtFile.Content.replacedtring(), Encoding.UTF8.GetString(returned.Skip(fieldSize).Take(txtFileSize).ToArray()));
            Aver.IsTrue(Azos.IOUtils.MemBufferEquals(partBinFile.Content as byte[], returned.Skip(fieldSize + txtFileSize).ToArray()));
          }
        }

19 Source : web.cs
with MIT License
from baibao132

internal HttpWebResponse CreateGetHttpResponse(string url)
        {
            HttpWebRequest request1 = (HttpWebRequest) WebRequest.Create(url);
            request1.Timeout = 0xbb8;
            request1.ContentType = "text/html;chartset=UTF-8";
            request1.UserAgent = "Mozilla / 5.0(Windows NT 10.0; Win64; x64; rv: 48.0) Gecko / 20100101 Firefox / 48.0";
            request1.Method = "GET";
            return (HttpWebResponse) request1.GetResponse();
        }

19 Source : web.cs
with MIT License
from baibao132

internal string Get(string URL, string Type)
        {
            string result = "";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
            var header = new WebHeaderCollection();
            header.Add(Type);
            req.Headers = header;

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

19 Source : web.cs
with MIT License
from baibao132

internal string Post(string URL, string jsonParas,string Type)
        {
            string result = "";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
            req.Method = "POST";
            req.ContentType = Type;
            req.Accept = Type;
            req.Headers.Add("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
            req.UserAgent = "Mozilla/5.0 (Windows NT 5.2; rv:12.0) Gecko/20100101 Firefox/12.0";
            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(jsonParas);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp;
            try { resp = (HttpWebResponse)req.GetResponse(); }
            catch (WebException ex) { resp = (HttpWebResponse)ex.Response; }
            //HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

19 Source : youdao.cs
with MIT License
from baibao132

public static string Get(string url)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            return result;
        }

19 Source : youdao.cs
with MIT License
from baibao132

protected string Post(string url, Dictionary<String, String> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                return result;
        }

19 Source : DownloadThread.cs
with MIT License
from baibao132

public void ThreadRun()
        {
            //task
            Thread td = new Thread(new ThreadStart(() =>
            {
                 if (downLength < block)//未下载完成
                {
                    try
                    {
                        int startPos = (int)(block * (threadId - 1) + downLength);//开始位置
                        int endPos = (int)(block * threadId - 1);//结束位置
                        Console.WriteLine("Thread " + this.threadId + " start download from position " + startPos + "  and endwith " + endPos);
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downUrl);
                        request.Referer = downUrl.ToString();
                        request.Method = "GET";
                        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";
                        request.AllowAutoRedirect = false;
                        request.ContentType = "application/octet-stream";
                        request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdoreplacedent, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                        request.Timeout = 10 * 1000;
                        request.AllowAutoRedirect = true;
                        request.AddRange(startPos, endPos);
                        //Console.WriteLine(request.Headers.ToString()); //输出构建的http 表头
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                        WebResponse wb = request.GetResponse();
                        using (Stream _stream = wb.GetResponseStream())
                        {
                            byte[] buffer = new byte[1024 * 50]; //缓冲区大小
                            long offset = -1;
                            using (Stream threadfile = new FileStream(this.saveFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) //设置文件以共享方式读写,否则会出现当前文件被另一个文件使用.
                            {
                                threadfile.Seek(startPos, SeekOrigin.Begin); //移动文件位置
                                while ((offset = _stream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    //offset 实际下载流大小
                                    downloader.append(offset); //更新已经下载当前总文件大小
                                    threadfile.Write(buffer, 0, (int)offset);
                                    downLength += offset;  //设置当前线程已下载位置
                                    downloader.update(this.threadId, downLength);
                                }
                                threadfile.Close(); //using 用完后可以自动释放..手动释放一遍.木有问题的(其实是多余的)
                                _stream.Close();
                                Console.WriteLine("Thread " + this.threadId + " download finish");
                                this.finish = true;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        this.downLength = -1;
                        Console.WriteLine("Thread " + this.threadId + ":" + e.Message);
                    }
                } 
            }));
            td.IsBackground = true;
            td.Start();
        }

19 Source : BacktraceApi.cs
with MIT License
from backtrace-labs

private BacktraceResult ReadServerResponse(HttpWebRequest request, BacktraceReport report)
        {
            using (WebResponse webResponse = request.GetResponse() as HttpWebResponse)
            {
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                string fullResponse = responseReader.ReadToEnd();
                var response = JsonConvert.DeserializeObject<BacktraceResult>(fullResponse);
                response.BacktraceReport = report;
                OnServerResponse?.Invoke(response);
                return response;
            }
        }

19 Source : Asr.cs
with Apache License 2.0
from Baidu-AIP

public JObject Recognize(Stream speech, string cuid, string format, int rate, int pid)
        {
            var asrBegin = new Dictionary<string, object>()
            {
                {"apikey", ApiKey},
                {"secretkey", SecretKey},
                {"appid", int.Parse(AppId)},
                {"cuid", cuid},
                {"sample_rate", rate},
                {"format", format},
                {"task_id", pid},
            };
            var asrBeginBodyStr = JsonConvert.SerializeObject(asrBegin, Formatting.None);
            var beginPktBytes = new TlvPacket(TlvType.AsrBegin, asrBeginBodyStr).ToBytes();

            var buf = new byte[AsrStreamingChunkDataSize];
            var bytesReadAmt = speech.Read(buf, 0, AsrStreamingChunkDataSize);
            if (bytesReadAmt == 0)
            {
                throw new AipException("Speech bytes stream empty");
            }

            var reqId = $"{Guid.NewGuid()}{Guid.NewGuid()}".Replace("-", "");
            var urlWithId = $"{UrlAsrStream}?id={reqId}";
            var req = (HttpWebRequest) WebRequest.Create(urlWithId);
            req.Method = "POST";
            req.ReadWriteTimeout = this.Timeout;
            req.Timeout = this.Timeout;
            req.SendChunked = true;
            req.AllowWriteStreamBuffering = false;
            req.ContentType = "application/octet-stream";

            var reqStream = req.GetRequestStream();
            reqStream.Write(beginPktBytes, 0, beginPktBytes.Length);
            while (bytesReadAmt > 0)
            {
                var doingPktBytes = new TlvPacket(TlvType.AsrData, buf, bytesReadAmt).ToBytes();
                reqStream.Write(doingPktBytes, 0, doingPktBytes.Length);
                bytesReadAmt = speech.Read(buf, 0, AsrStreamingChunkDataSize);
            }

            var endPktBytes = new TlvPacket(TlvType.AsrEnd).ToBytes();
            reqStream.Write(endPktBytes, 0, endPktBytes.Length);
            reqStream.Close();
            var resp = ((HttpWebResponse) req.GetResponse()).GetResponseStream();

            var buf2 = Utils.StreamToBytes(resp);
            var respPackets = TlvPacket.ParseFromBytes(buf2).ToList();

            if (respPackets.Count == 0)
            {
                throw new AipException("Server return empty");
            }

            var respStr = "";
            try
            {
                respStr = System.Text.Encoding.UTF8.GetString(respPackets[0].V);
                var respObj = JsonConvert.DeserializeObject(respStr) as JObject;
                return respObj;
            }
            catch (Exception e)
            {
                // 非json应该抛异常
                throw new AipException($"{e.Message}{respStr}");
            }
        }

19 Source : AipServiceBase.cs
with Apache License 2.0
from Baidu-AIP

protected HttpWebResponse SendRequetRaw(AipHttpRequest aipRequest)
        {
            var webReq = GenerateWebRequest(aipRequest);
            Log(webReq.RequestUri.ToString());
            HttpWebResponse resp;
            try
            {
                resp = (HttpWebResponse) webReq.GetResponse();
            }
            catch (WebException e)
            {
                // 网络请求失败应该抛异常
                throw new AipException((int) e.Status, e.Message);
            }

            if (resp.StatusCode != HttpStatusCode.OK)
                throw new AipException((int) resp.StatusCode, "Server response code:" + (int) resp.StatusCode);

            return resp;
        }

See More Examples