System.Net.WebRequest.CreateHttp(string)

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

175 Examples 7

19 View Source File : PrimitiveMethods.Download.cs
License : MIT License
Project Creator : Accelerider

public static HttpWebRequest ToRequest(this string remotePath)
        {
            return WebRequest.CreateHttp(remotePath);
        }

19 View Source File : Comment.cs
License : MIT License
Project Creator : AlaricGilbert

public static async Task<string> SendAsync(string av_number, string comment)
        {
            var req = WebRequest.CreateHttp($"https://api.bilibili.com/x/v2/reply/add?oid={av_number}&type=1&message={comment}&plat=1&jsonp=jsonp&csrf={Account.CookieJObjet["bili_jct"].Value<string>()}");
            req.Method = "POST";
            req.Host = "api.bilibili.com";
            //req.Connection = "keep-alive";
            req.Accept = "application/json, text/javascript, */*; q=0.01";
            req.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Referer = "https://www.bilibili.com/video/av" + av_number;
            req.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            req.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            req.Headers.Add("Cookie", Account.CookieString);
            var response = await req.GetResponseAsync();
            var r_stream = response.GetResponseStream();
            byte[] buffer = new byte[response.ContentLength];
            r_stream.ReadAsync(buffer, 0, (int)response.ContentLength).Wait();
            return Encoding.UTF8.GetString(buffer);
        }

19 View Source File : MKMInteract.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

public static XmlDoreplacedent MakeRequest(string url, string method, string body = null)
      {
        // throw the exception ourselves to prevent sending requests to MKM that would end with this error 
        // because MKM tends to revoke the user's app token if it gets too many requests above the limit
        // the 429 code is the same MKM uses for this error
        if (denyAdditionalRequests)
        {
          // MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day
          // the denial was triggered, that means the 0:00 CET has preplaceded and we can reset the deny
          if (DateTime.UtcNow.Date == denyTime.Date && DateTime.UtcNow.Hour < 22)
            throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset.");
          else
            denyAdditionalRequests = false;
        }
        // enforce the maxRequestsPerMinute limit - technically it's just an approximation as the requests
        // can arrive to MKM with some delay, but it should be close enough
        var now = DateTime.Now;
        while (requestTimes.Count > 0 && (now - requestTimes.Peek()).TotalSeconds > 60)
        {
          requestTimes.Dequeue();// keep only times of requests in the past 60 seconds
        }
        if (requestTimes.Count >= maxRequestsPerMinute)
        {
          // wait until 60.01 seconds preplaceded since the oldest request
          // we know (now - peek) is <= 60, otherwise it would get dequeued above,
          // so we are preplaceding a positive number to sleep
          System.Threading.Thread.Sleep(
              60010 - (int)(now - requestTimes.Peek()).TotalMilliseconds);
          requestTimes.Dequeue();
        }

        requestTimes.Enqueue(DateTime.Now);
        XmlDoreplacedent doc = new XmlDoreplacedent();
        for (int numAttempts = 0; numAttempts < MainView.Instance.Config.MaxTimeoutRepeat; numAttempts++)
        {
          try
          {
            var request = WebRequest.CreateHttp(url);
            request.Method = method;

            request.Headers.Add(HttpRequestHeader.Authorization, header.GetAuthorizationHeader(method, url));
            request.Method = method;

            if (body != null)
            {
              request.ServicePoint.Expect100Continue = false;
              request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(body);
              request.ContentType = "text/xml";

              var writer = new StreamWriter(request.GetRequestStream());

              writer.Write(body);
              writer.Close();
            }

            var response = request.GetResponse() as HttpWebResponse;

            // just for checking EoF, it is not accessible directly from the Stream object
            // Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets). 
            // Preplaceding empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser 
            // even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty
            StreamReader s = new StreamReader(response.GetResponseStream());
            if (!s.EndOfStream)
              doc.Load(s);
            s.Close();
            int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count"));
            int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max"));
            if (requestCount >= requestLimit)
            {
              denyAdditionalRequests = true;
              denyTime = DateTime.UtcNow;
            }
            MainView.Instance.Invoke(new MainView.UpdateRequestCountCallback(MainView.Instance.UpdateRequestCount), requestCount, requestLimit);
            break;
          }
          catch (WebException webEx)
          {
            // timeout can be either on our side (Timeout) or on server
            bool isTimeout = webEx.Status == WebExceptionStatus.Timeout;
            if (webEx.Status == WebExceptionStatus.ProtocolError)
            {
              if (webEx.Response is HttpWebResponse response)
              {
                isTimeout = response.StatusCode == HttpStatusCode.GatewayTimeout
                    || response.StatusCode == HttpStatusCode.ServiceUnavailable;
              }
            }
            // handle only timeouts, client handles other exceptions
            if (isTimeout && numAttempts + 1 < MainView.Instance.Config.MaxTimeoutRepeat)
              System.Threading.Thread.Sleep(1500); // wait and try again
            else
              throw webEx;
          }
        }
        return doc;
      }

19 View Source File : WebRequests.cs
License : MIT License
Project Creator : angelsix

public static async Task<HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action<HttpWebRequest> configureRequest = null, string bearerToken = null)
        {
            #region Setup

            // Create the web request
            var request = WebRequest.CreateHttp(url);

            // Make it a POST request method
            request.Method = HttpMethod.Post.ToString();

            // Set the appropriate return type
            request.Accept = returnType.ToMimeString();

            // Set the content type
            request.ContentType = sendType.ToMimeString();

            // If we have a bearer token...
            if (bearerToken != null)
                // Add bearer token to header
                request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}");

            // Any custom work
            configureRequest?.Invoke(request);

            #endregion

            #region Write Content

            // Set the content length
            if (content == null)
            {
                // Set content length to 0
                request.ContentLength = 0;
            }
            // Otherwise...
            else
            {
                // Create content to write
                var contentString = string.Empty;

                // Serialize to Json?
                if (sendType == KnownContentSerializers.Json)
                    // Serialize content to Json string
                    contentString = JsonConvert.SerializeObject(content);
                // Serialize to Xml?
                else if (sendType == KnownContentSerializers.Xml)
                {
                    // Create Xml serializer
                    var xmlSerializer = new XmlSerializer(content.GetType());

                    // Create a string writer to receive the serialized string
                    using (var stringWriter = new StringWriter())
                    {

                        // Serialize the object to a string
                        xmlSerializer.Serialize(stringWriter, content);

                        // Extract the string from the writer
                        contentString = stringWriter.ToString();
                    }
                }
                // Currently unknown
                else
                {
                    // TODO: Throw error once we have Dna Framework exception types
                }

                // 
                //  NOTE: This GetRequestStreamAsync could throw with a
                //        SocketException (or an inner exception of SocketException)
                //
                //        However, we cannot return anything useful from this 
                //        so we just let it throw out so the caller can handle
                //        this (the other PostAsync call for example).
                //
                //        SocketExceptions are a good indication there is no 
                //        Internet, or no connection or firewalls blocking 
                //        communication.
                //

                // Get body stream...
                using (var requestStream = await request.GetRequestStreamAsync())
                // Create a stream writer from the body stream...
                using (var streamWriter = new StreamWriter(requestStream))
                    // Write content to HTTP body stream
                    await streamWriter.WriteAsync(contentString);
            }

            #endregion

            // Wrap call...
            try
            {
                // Return the raw server response
                return await request.GetResponseAsync() as HttpWebResponse;
            }
            // Catch Web Exceptions (which throw for things like 401)
            catch (WebException ex)
            {
                // If we got a response...
                if (ex.Response is HttpWebResponse httpResponse)
                    // Return the response
                    return httpResponse;

                // Otherwise, we don't have any information to be able to return
                // So re-throw
                throw;
            }
        }

19 View Source File : WebRequests.cs
License : MIT License
Project Creator : angelsix

public static async Task<HttpWebResponse> GetAsync(string url, Action<HttpWebRequest> configureRequest = null, string bearerToken = null)
        {
            #region Setup

            // Create the web request
            var request = WebRequest.CreateHttp(url);

            // Make it a GET request method
            request.Method = HttpMethod.Get.ToString();

            // If we have a bearer token...
            if (bearerToken != null)
                // Add bearer token to header
                request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}");

            // Any custom work
            configureRequest?.Invoke(request);

            #endregion
            
            // Wrap call...
            try
            {
                // Return the raw server response
                return await request.GetResponseAsync() as HttpWebResponse;
            }
            // Catch Web Exceptions (which throw for things like 401)
            catch (WebException ex)
            {
                // If we got a response...
                if (ex.Response is HttpWebResponse httpResponse)
                    // Return the response
                    return httpResponse;

                // Otherwise, we don't have any information to be able to return
                // So re-throw
                throw;
            }
        }

19 View Source File : ConnectivityHelper.cs
License : MIT License
Project Creator : AnnoDesigner

public static async Task<bool> IsConnected()
        {
            var result = false;

            var isInternetAvailable = false;

            var request = WebRequest.CreateHttp(URL);
            request.Timeout = TimeSpan.FromSeconds(5).Milliseconds;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = REQUEST_METHOD_HEAD;

            try
            {
                using (var response = (HttpWebResponse)await request.GetResponseAsync().ConfigureAwait(false))
                {
                    isInternetAvailable = response.StatusCode == HttpStatusCode.OK;
                }
            }
            catch (WebException)
            {
                isInternetAvailable = false;
            }

            //service outage? try second url
            if (!isInternetAvailable)
            {
                request = WebRequest.CreateHttp(SECOND_URL);
                request.Timeout = TimeSpan.FromSeconds(5).Milliseconds;
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Method = REQUEST_METHOD_HEAD;

                try
                {
                    using (var response = (HttpWebResponse)await request.GetResponseAsync().ConfigureAwait(false))
                    {
                        isInternetAvailable = response.StatusCode == HttpStatusCode.OK;
                    }
                }
                catch (WebException)
                {
                    isInternetAvailable = false;
                }
            }

            if (isInternetAvailable)
            {
                result = IsNetworkAvailable;
            }

            return result;
        }

19 View Source File : ProductionServerCertificates.cs
License : MIT License
Project Creator : 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 View Source File : DaumCafeSession.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task Authenticate(CancellationToken ct)
        {
            async Task<string> GetFuid()
            {
                var request = WebRequest.CreateHttp("https://logins.daum.net/accounts/signinform.do");
                request.Method = "GET";
                request.Headers["Connection"] = "keep-alive";
                request.Headers["Cache-Control"] = "max-age=0";
                request.Headers["Upgrade-Insecure-Requests"] = "1";
                request.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
                request.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
                request.Headers["Accept-Encoding"] = "gzip, deflate, br";
                request.Headers["Accept-Language"] = "en,cs-CZ;q=0.9,cs;q=0.8";

                using (var response = await request.GetResponseAsync(ct))
                using (var stream = response.GetResponseStream())
                using (var gzipStream = new GZipStream(stream, CompressionMode.Decompress))
                using (var reader = new StreamReader(gzipStream))
                {
                    var content = await reader.ReadToEndAsync();

                    var doc = new HtmlDoreplacedent();
                    doc.LoadHtml(content);

                    return doc.DoreplacedentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "") == "fuid")?.GetAttributeValue("value", "");
                }
            }

            var fuid = await GetFuid();
            if (string.IsNullOrWhiteSpace(fuid))
                throw new NodeNotFoundException("Cannot find FUID.");

            var request = WebRequest.CreateHttp($"https://logins.daum.net/accounts/login.do");
            request.Method = "POST";
            request.Headers["Connection"] = "keep-alive";
            request.Headers["Cache-Control"] = "max-age=0";
            request.Headers["Origin"] = "https://logins.daum.net";
            request.Headers["Upgrade-Insecure-Requests"] = "1";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"; // required
            request.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            request.Headers["Referer"] = "https://logins.daum.net/accounts/signinform.do"; // required
            request.Headers["Accept-Encoding"] = "gzip, deflate, br";
            request.Headers["Accept-Language"] = "en,cs-CZ;q=0.9,cs;q=0.8";
                
            request.CookieContainer = new CookieContainer();

            using (var stream = await request.GetRequestStreamAsync())
            using (var writer = new StreamWriter(stream, System.Text.Encoding.ASCII, 1, false))
            {
                await writer.WriteAsync($"url=https%3A%2F%2Fwww.daum.net%2F&relative=&weblogin=1&service=&fuid={fuid}&slevel=1&finaldest=&reloginSeq=0&id={_credential.Item1}&pw=");
                await _credential.Item2.ForEach(async x => { await writer.WriteAsync((char)x); });
            }

            using (var response = await request.GetResponseAsync(ct))
            {
                // Expire old cookies
                foreach (Cookie cookie in _handler.CookieContainer.GetCookies(new Uri("https://daum.net")))
                    cookie.Expired = true;

                if (response.ResponseUri.ToString().Contains("releasecountryrestrict"))
                    throw new CountryBlockException(); // Failed because of logging in from a different country

                if (response.Cookies.Count <= 0)
                    throw new LoginFailedException();

                // Add new cookies
                foreach (Cookie cookie in response.Cookies)
                    _handler.CookieContainer.Add(new Uri($"https://{cookie.Domain}{cookie.Path}"), cookie);
            }
        }

19 View Source File : BitlyUrlShortener.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<string> ShortenAsync(string url)
        {
            var request = WebRequest.CreateHttp("https://api-ssl.bitly.com/v4/bitlinks");
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Headers["Authorization"] = "Bearer " + _apiKey;

            using (var writer = new StreamWriter(await request.GetRequestStreamAsync(), Encoding.ASCII))
                await writer.WriteAsync("{\"long_url\": \"" + url + "\"}");

            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var content = await reader.ReadToEndAsync();
                var o = JObject.Parse(content);

                return (string)o["link"];
            }
        }

19 View Source File : PolrUrlShortener.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<string> ShortenAsync(string url)
        {
            var request = WebRequest.CreateHttp($"{_domain}/api/v2/action/shorten?key={_apiKey}&url={Uri.EscapeDataString(url)}&is_secret=false");

            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                return await reader.ReadToEndAsync();
            }
        }

19 View Source File : SpotifyClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<string> SearchTrackId(string query)
        {
            var request = WebRequest.CreateHttp($"https://api.spotify.com/v1/search?q={Uri.EscapeDataString(query)}&type=track&limit=1");
            request.Headers.Add("Authorization", $"Bearer {await GetToken()}");

            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                dynamic root = JObject.Parse(text);
                dynamic item = (root.tracks?.items as JArray)?.FirstOrDefault();
                return (string)item?.id;
            }
        }

19 View Source File : SpotifyHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public static async Task<(string Token, int ExpiresIn)> RefreshToken(string refreshToken, string clientId, string clientSecret)
        {
            var request = WebRequest.CreateHttp("https://accounts.spotify.com/api/token");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Authorization", BuildAuthorizationHeader(clientId, clientSecret));

            using (var writer = new StreamWriter(await request.GetRequestStreamAsync(), Encoding.ASCII))
            {
                await writer.WriteAsync($"grant_type=refresh_token&refresh_token={refreshToken}");
            }

            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var root = JObject.Parse(text);
                return ((string)root["access_token"], (int)root["expires_in"]);
            }
        }

19 View Source File : StarboardModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private async Task<string> ResolveInstagramThumbnailAsync(string baseUrl)
        {
            try
            {
                var currentUrl = baseUrl;
                var redirectCodes = new[] { HttpStatusCode.MovedPermanently, HttpStatusCode.Redirect };
                for (int i = 0; i < 8; ++i)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(currentUrl))
                            break;

                        var request = WebRequest.CreateHttp(currentUrl);
                        request.Method = "GET";
                        request.AllowAutoRedirect = false;

                        using (var response = await request.GetResponseAsync())
                        {
                            return currentUrl;
                        }
                    }
                    catch (WebException ex) when (ex.Response is HttpWebResponse r && redirectCodes.Contains(r.StatusCode))
                    {
                        currentUrl = r.Headers["Location"];
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to resolve instagram thumbnail {UrlString}", baseUrl);
            }

            return null;
        }

19 View Source File : TranslatorModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

[Command("translate", "Translates a piece of text.")]
        [Alias("tr"), Alias("번역")]
        [Parameter("From", LanguageRegex, ParameterType.String, "the language of the message")]
        [Parameter("To", LanguageRegex, ParameterType.String, "the language to translate into")]
        [Parameter("Message", ParameterType.String, ParameterFlags.Remainder, "the word or sentence you want to translate")]
        [Comment("Korean = `ko` \nreplacedan = `ja` \nEnglish = `en` \nChinese(Simplified) = `zh-CH` \nChinese(Traditional) = `zh-TW` \nSpanish = `es` \nFrench = `fr` \nGerman = `de` \nRussian = `ru` \nPortuguese = `pt` \nItalian = `it` \nVietnamese = `vi` \nThai = `th` \nIndonesian = `id`")]
        [Example("ko en 사랑해")]
        public async Task Translate(ICommand command, ILogger logger)
        {
            await command.Message.Channel.TriggerTypingAsync();
            var stringMessage = command["Message"].ToString();
            var firstLang = command["From"].ToString();
            var lastLang = command["To"].ToString();

            var byteDataParams = Encoding.UTF8.GetBytes($"source={Uri.EscapeDataString(firstLang)}&target={Uri.EscapeDataString(lastLang)}&text={Uri.EscapeDataString(stringMessage)}");

            try
            {
                var request = WebRequest.CreateHttp("https://openapi.naver.com/v1/papago/n2mt");
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("X-Naver-Client-Id", _integrationOptions.Value.PapagoClientId);
                request.Headers.Add("X-Naver-Client-Secret", _integrationOptions.Value.PapagoClientSecret);
                request.ContentLength = byteDataParams.Length;
                using (var st = request.GetRequestStream())
                {
                    st.Write(byteDataParams, 0, byteDataParams.Length);
                }

                using (var responseClient = await request.GetResponseAsync())
                using (var reader = new StreamReader(responseClient.GetResponseStream()))
                {
                    var parserObject = JObject.Parse(await reader.ReadToEndAsync());
                    var trMessage = parserObject["message"]["result"]["translatedText"].ToString();

                    var translateSentence = trMessage.Truncate(EmbedBuilder.MaxDescriptionLength);

                    EmbedBuilder embedBuilder = new EmbedBuilder()
                        .Withreplacedle($"Translation from **{firstLang.ToUpper()}** to **{lastLang.ToUpper()}**")
                        .WithDescription(translateSentence)
                        .WithColor(new Color(0, 206, 56))
                        .WithFooter("Powered by Papago");

                    await command.Reply(embedBuilder.Build());
                }
            }
            catch (WebException ex) when (ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.BadRequest)
            {
                throw new IncorrectParametersCommandException("Unsupported language combination.");
            }
            catch (WebException ex)
            {
                logger.LogError(ex, "Failed to reach Papago");
                await command.Reply($"Couldn't reach Papago (error {(ex.Response as HttpWebResponse)?.StatusCode.ToString() ?? ex.Status.ToString()}). Please try again in a few seconds.");
            }
        }

19 View Source File : SpotifyClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<string> SearchTrackUrl(string query)
        {
            var request = WebRequest.CreateHttp($"https://api.spotify.com/v1/search?q={Uri.EscapeDataString(query)}&type=track&limit=1");
            request.Headers.Add("Authorization", $"Bearer {await GetToken()}");

            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                dynamic root = JObject.Parse(text);
                dynamic item = (root.tracks?.items as JArray)?.FirstOrDefault();
                return (string)item?.external_urls?.spotify;
            }
        }

19 View Source File : SpotifyHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public static async Task<(string Token, int ExpiresIn)> GetClientToken(string clientId, string clientSecret)
        {
            var request = WebRequest.CreateHttp("https://accounts.spotify.com/api/token");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Authorization", BuildAuthorizationHeader(clientId, clientSecret));

            using (var writer = new StreamWriter(await request.GetRequestStreamAsync(), Encoding.ASCII))
                await writer.WriteAsync("grant_type=client_credentials");

            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                dynamic root = JObject.Parse(text);
                return ((string)root["access_token"], (int)root["expires_in"]);
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<LastFmUserInfo> GetUserInfo()
        {
            var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getinfo&user={User}&api_key={Key}&format=json");
            request.Timeout = (int)RequestTimeout.TotalMilliseconds;
            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var user = JObject.Parse(text)["user"];

                return new LastFmUserInfo((int?)user["playcount"] ?? 0);
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<(IReadOnlyCollection<LastFmRecentTrack> tracks, bool remaining)> GetRecentTracksPage(int page, int count, DateTimeOffset? from = null)
        {
            var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getrecenttracks&user={User}&api_key={Key}&format=json&limit={count}&page={page}&extended=1" + (from.HasValue ? $"&from={from.Value.ToUnixTimeSeconds()}" : string.Empty));
            request.Timeout = (int)RequestTimeout.TotalMilliseconds;
            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var root = JObject.Parse(text);
                var tracks = root["recenttracks"]?["track"] as JArray;

                if (tracks != null && tracks.Any())
                {
                    var nowPlaying = page == 1 && string.Compare((string)tracks[0]["@attr"]?["nowplaying"], "true", true) == 0;
                    var result = tracks.Select((x, i) =>
                    {
                        var uts = (long?)x["date"]?["uts"];
                        return new LastFmRecentTrack(
                            (string)x["name"],
                            i == 0 && nowPlaying, 
                            (string)x["artist"]?["name"], 
                            (string)x["album"]?["#text"],
                            GetLargestImage(x["image"]),
                            uts.HasValue ? DateTimeOffset.FromUnixTimeSeconds(uts.Value) : (DateTimeOffset?)null);
                    });
                    
                    var more = page < (int)root["recenttracks"]["@attr"]["totalPages"];
                    return (result.ToList(), more);
                }
                else
                {
                    return (Array.Empty<LastFmRecentTrack>(), false);
                }
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<LastFmArtist> GetArtistInfo(string name)
        {
            var request = WebRequest.CreateHttp($"{ApiBase}/?method=artist.getInfo&api_key={Key}&artist={Uri.EscapeDataString(name)}&format=json&username={User}");
            request.Timeout = (int)RequestTimeout.TotalMilliseconds;
            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var artist = JObject.Parse(text)?["artist"];
                if (artist == null)
                    return null;

                return new LastFmArtist((string)artist["name"], imageUri: GetLargestImage(artist["image"]));
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<LastFmTrack> GetTrackInfo(string artistName, string name)
        {
            var request = WebRequest.CreateHttp($"{ApiBase}/?method=track.getInfo&api_key={Key}&artist={Uri.EscapeDataString(artistName)}&track={Uri.EscapeDataString(name)}&format=json&username={User}");
            request.Timeout = (int)RequestTimeout.TotalMilliseconds;
            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var track = JObject.Parse(text)?["track"];
                if (track == null)
                    return null;

                var artist = new LastFmArtist((string)track["artist"]["name"]);
                var album = new LastFmAlbum((string)track["album"]?["replacedle"], artist, imageUri: GetLargestImage(track["album"]?["image"]));
                return new LastFmTrack((string)track["name"], album, (int?)track["userplaycount"]);
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<IEnumerable<LastFmArtist>> GetTopArtists(LastFmDataPeriod period, int count)
        {
            if (period == LastFmDataPeriod.Day)
            {
                var tracks = await GetRecentTracks(StatsPeriodTimeMapping[period]);
                return tracks
                    .SkipWhile(x => x.NowPlaying)
                    .GroupBy(x => x.Artist.Id)
                    .Select(x => x.First().Artist.WithPlaycount(x.Count()))
                    .OrderByDescending(x => x.Playcount);
            }
            else
            {
                var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.gettopartists&user={User}&api_key={Key}&period={StatsPeriodMapping[period]}&limit={count}&format=json");
                request.Timeout = (int)RequestTimeout.TotalMilliseconds;
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = await reader.ReadToEndAsync();
                    var root = JObject.Parse(text);
                    var results = root?["topartists"]?["artist"] as JArray ?? Enumerable.Empty<JToken>();
                    return results.Select(x => new LastFmArtist((string)x["name"], (int)x["playcount"]));
                }
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<IEnumerable<LastFmAlbum>> GetTopAlbums(LastFmDataPeriod period, int count)
        {
            if (period == LastFmDataPeriod.Day)
            {
                var tracks = await GetRecentTracks(StatsPeriodTimeMapping[period]);
                return tracks
                    .SkipWhile(x => x.NowPlaying)
                    .GroupBy(x => x.Album.Id)
                    .Select(x => x.First().Album.WithPlaycount(x.Count()))
                    .OrderByDescending(x => x.Playcount);
            }
            else
            {
                var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.gettopalbums&user={User}&api_key={Key}&period={StatsPeriodMapping[period]}&limit={count}&format=json");
                request.Timeout = (int)RequestTimeout.TotalMilliseconds;
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = await reader.ReadToEndAsync();
                    var root = JObject.Parse(text);
                    var results = root?["topalbums"]?["album"] as JArray ?? Enumerable.Empty<JToken>();
                    return results.Select(x => new LastFmAlbum((string)x["name"], new LastFmArtist((string)x["artist"]["name"]), (int)x["playcount"]));
                }
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<IEnumerable<LastFmTrack>> GetTopTracks(LastFmDataPeriod period, int count = int.MaxValue, CancellationToken ct = default)
        {
            if (period == LastFmDataPeriod.Day)
            {
                var tracks = await GetRecentTracks(StatsPeriodTimeMapping[period]);
                return tracks
                    .SkipWhile(x => x.NowPlaying)
                    .GroupBy(x => x.Id)
                    .Select(x => x.First().ToTrack(x.Count()))
                    .OrderByDescending(x => x.Playcount);
            }
            else
            {
                var retrieved = 0;
                var page = 1;
                var results = Enumerable.Empty<LastFmTrack>();
                var pageSize = Math.Min(count, MaxTopPageSize);
                while (retrieved < count)
                {
                    ct.ThrowIfCancellationRequested();
                    var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.gettoptracks&user={User}&api_key={Key}&period={StatsPeriodMapping[period]}&limit={pageSize}&page={page}&format=json");
                    request.Timeout = (int)RequestTimeout.TotalMilliseconds;
                    using (var response = (HttpWebResponse)await request.GetResponseAsync())
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        ct.ThrowIfCancellationRequested();
                        var text = await reader.ReadToEndAsync();
                        ct.ThrowIfCancellationRequested();

                        var root = JObject.Parse(text);
                        var pageResults = (root?["toptracks"]?["track"] as JArray ?? Enumerable.Empty<JToken>()).ToList();
                        results = results.Concat(pageResults.Select(x => new LastFmTrack((string)x["name"], new LastFmAlbum(null, new LastFmArtist((string)x["artist"]["name"]), null), (int)x["playcount"])));

                        retrieved += pageResults.Count;
                        var more = page < ((int?)root?["toptracks"]?["@attr"]?["totalPages"] ?? 1);
                        if (!more || !pageResults.Any())
                            break;
                    }

                    page++;
                }

                return results;
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<int> GetTotalPlaycount(DateTimeOffset? from = null)
        {
            var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getrecenttracks&user={User}&api_key={Key}&limit=1&format=json" + (from.HasValue ? $"&from={from.Value.ToUnixTimeSeconds()}" : string.Empty));
            request.Timeout = (int)RequestTimeout.TotalMilliseconds;
            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var root = JObject.Parse(text);
                return (int)root["recenttracks"]["@attr"]["total"];
            }
        }

19 View Source File : LastFmClient.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public async Task<LastFmArtistDetail> GetArtistDetail(string artist, LastFmDataPeriod period)
        {
            try
            {
                var infoTask = GetArtistInfo(artist);
                var request = WebRequest.CreateHttp($"https://www.last.fm/user/{User}/library/music/{Uri.EscapeDataString(artist)}?date_preset={StatsPeriodWebMapping[period]}");
                request.Timeout = (int)RequestTimeout.TotalMilliseconds;
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var content = await reader.ReadToEndAsync();

                    var doc = new HtmlDoreplacedent();
                    doc.LoadHtml(content);

                    // Get artist info
                    var info = await infoTask;
                    if (info == null)
                        return null;

                    // Get avatar (we can't get it via the API because it never actually has the artist's image...)
                    var image = doc.DoreplacedentNode.Descendants("span")
                        .FirstOrDefault(x => x.HasClreplaced("library-header-image"))?
                        .Descendants("img")
                        .FirstOrDefault()?
                        .GetAttributeValue("src", null)?
                        .Replace("avatar70s", "avatar170s");

                    // Get playcount and count of listened albums and tracks (in that order)
                    var metadata = doc.DoreplacedentNode
                        .Descendants("p")
                        .Where(x => x.HasClreplaced("metadata-display") && x.ParentNode.HasClreplaced("metadata-item"))
                        .Select(x => int.Parse(x.InnerText, System.Globalization.NumberStyles.Any, new System.Globalization.CultureInfo("en-US")))
                        .ToList();

                    var playcount = metadata.ElementAtOrDefault(0);
                    var albumsListened = metadata.ElementAtOrDefault(1);
                    var tracksListened = metadata.ElementAtOrDefault(2);

                    // Get top albums and tracks
                    IEnumerable<(string name, string url, int playcount)> GetTopLisreplacedems(HtmlNode topList)
                    {
                        foreach (var item in topList.Descendants("tr").Where(x => x.HasClreplaced("chartlist-row") || x.HasClreplaced("chartlist-row\n")))
                        {
                            var itemNameLink = item.Descendants("td").First(x => x.HasClreplaced("chartlist-name")).Descendants("a").First();
                            var itemUrl = "https://www.last.fm" + itemNameLink.GetAttributeValue("href", null);

                            var scrobbleText = item.Descendants("span").First(x => x.HasClreplaced("chartlist-count-bar-value")).InnerText;
                            var scrobbleCount = int.Parse(Regex.Match(scrobbleText, @"[\d,.\s]+").Value, System.Globalization.NumberStyles.Any, new System.Globalization.CultureInfo("en-US"));
                            yield return (WebUtility.HtmlDecode(itemNameLink.InnerText), itemUrl, scrobbleCount);
                        }
                    }

                    var topLists = doc.DoreplacedentNode.Descendants("table").Where(x => x.HasClreplaced("chartlist") || x.HasClreplaced("chartlist\n")).ToList();
                    var topAlbums = Enumerable.Empty<LastFmAlbum>();
                    if (topLists.Any())
                        topAlbums = GetTopLisreplacedems(topLists.First()).Select(x => new LastFmAlbum(x.name, info, x.playcount));

                    var topTracks = Enumerable.Empty<LastFmTrack>();
                    if (topLists.Skip(1).Any())
                        topTracks = GetTopLisreplacedems(topLists.Skip(1).First()).Select(x => new LastFmTrack(x.name, new LastFmAlbum(null, info), x.playcount));

                    var imageUri = string.IsNullOrEmpty(image) ? null : new Uri(image);
                    return new LastFmArtistDetail(info, imageUri, topAlbums, topTracks, albumsListened, tracksListened, playcount);
                }
            }
            catch (WebException e) when ((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                return null;
            }
        }

19 View Source File : API.cs
License : MIT License
Project Creator : AyrA

private static WebRequest Req(string method, Dictionary<string, object> values = null)
        {
            if (ApiKey != API_ANONYMOUS_KEY)
            {
                SatisfactorySaveEditor.FeatureReport.Used(SatisfactorySaveEditor.FeatureReport.Feature.ApiAction);
            }
            var Request = WebRequest.CreateHttp(API_API + "/" + method);
            Request.Method = "POST";
            Request.ContentType = "application/x-www-form-urlencoded";

            if (values == null)
            {
                values = new Dictionary<string, object>();
            }
            //Overwrite attempts to use a custom key
            values["key"] = ApiKey;
            List<string> Chain = new List<string>();
            foreach (var KV in values)
            {
                //Key is always a string
                var Key = Uri.EscapeDataString(KV.Key == null ? string.Empty : KV.Key);
                object Value = KV.Value;
                //Add array entries multiple times according to the API spec
                if (Value != null && Value.GetType().IsArray)
                {
                    foreach (var V in (Array)Value)
                    {
                        //Add array values as array
                        Chain.Add(string.Format(
                            "{0}[]={1}", Key,
                            Uri.EscapeDataString(V == null ? string.Empty : V.ToString())));
                    }
                }
                else
                {
                    //Add signle value as-is
                    Chain.Add(string.Format(
                        "{0}={1}", Key,
                        Value == null ? string.Empty : Value));
                }
            }
            //Build request body string
            var Data = Encoding.UTF8.GetBytes(string.Join("&", Chain));
            //Set precomputed data length
            Request.ContentLength = Data.Length;

            //Write data
            using (var S = Request.GetRequestStream())
            {
                S.Write(Data, 0, Data.Length);
            }

            //Return processed request
            return Request;
        }

19 View Source File : API.cs
License : MIT License
Project Creator : 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 View Source File : API.cs
License : MIT License
Project Creator : 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 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : FeatureReport.cs
License : MIT License
Project Creator : 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 View Source File : UpdateHandler.cs
License : MIT License
Project Creator : AyrA

private static HttpWebRequest GetReq(string URL)
        {
            var Req = WebRequest.CreateHttp(URL);
            Req.UserAgent = UserAgent;
            return Req;
        }

19 View Source File : DummyFileControllerTest.cs
License : MIT License
Project Creator : bezzad

private WebHeaderCollection ReadAndGetHeaders(string url, byte[] bytes)
        {
            HttpWebRequest request = WebRequest.CreateHttp(url);
            using HttpWebResponse downloadResponse = request.GetResponse() as HttpWebResponse;
            var respStream = downloadResponse.GetResponseStream();
            respStream.Read(bytes);

            return downloadResponse.Headers;
        }

19 View Source File : AnnouncerClient.cs
License : MIT License
Project Creator : BigETI

public Task<HttpStatusCode> AnnounceAsync()
        {
            Task<HttpStatusCode> ret = new Task<HttpStatusCode>(() =>
            {
                HttpStatusCode r = HttpStatusCode.BadRequest;
                try
                {
                    if ((Port != 0) && (!(string.IsNullOrWhiteSpace(Host))))
                    {
                        StringBuilder uri_builder = null;
                        switch (API)
                        {
                            case EAnnouncerAPI.Legacy:
                                if (!(string.IsNullOrWhiteSpace(Version)))
                                {
                                    uri_builder = new StringBuilder();
                                    uri_builder.Append(UseHTTPS ? "https://" : "http://");
                                    uri_builder.Append(Host);
                                    uri_builder.Append("/");
                                    uri_builder.Append(Version);
                                    uri_builder.Append("/announce/");
                                    uri_builder.Append(Port.ToString());
                                }
                                break;
                            case EAnnouncerAPI.SAMPServersAPI:
                                if (!(string.IsNullOrWhiteSpace(IPv4Address)))
                                {
                                    uri_builder = new StringBuilder();
                                    uri_builder.Append(UseHTTPS ? "https://" : "http://");
                                    uri_builder.Append(Host);
                                    uri_builder.Append("/v2/server");
                                }
                                break;
                            case EAnnouncerAPI.SACNRMonitorAPI:
                                if (!(string.IsNullOrWhiteSpace(IPv4Address)))
                                {
                                    uri_builder = new StringBuilder();
                                    uri_builder.Append(UseHTTPS ? "https://" : "http://");
                                    uri_builder.Append(Host);
                                    uri_builder.Append("/api/?Action=announce");
                                }
                                break;
                        }
                        if (uri_builder != null)
                        {
                            HttpWebRequest http_web_request = WebRequest.CreateHttp(uri_builder.ToString());
                            if (http_web_request != null)
                            {
                                Log("Requesting with method \"" + Method + "\" at \"" + http_web_request.Address + "\" with API \"" + API + "\"...", false);
                                http_web_request.AllowAutoRedirect = false;
                                http_web_request.Headers.Add(HttpRequestHeader.Host, Host);
                                if (!(string.IsNullOrWhiteSpace(UserAgent)))
                                {
                                    http_web_request.UserAgent = UserAgent;
                                }
                                if (!(string.IsNullOrWhiteSpace(Referer)))
                                {
                                    http_web_request.Referer = Referer;
                                }
                                http_web_request.Accept = "*/*";
                                http_web_request.Method = Method;
                                switch (API)
                                {
                                    case EAnnouncerAPI.SAMPServersAPI:
                                        http_web_request.ContentType = ((CustomServerInfo == null) ? "application/x-www-form-urlencoded" : "application/json");
                                        using (Stream request_stream = http_web_request.GetRequestStream())
                                        {
                                            if (CustomServerInfo == null)
                                            {
                                                StreamWriter request_memory_writer = new StreamWriter(request_stream);
                                                request_memory_writer.Write("address=");
                                                request_memory_writer.Write(IPv4Address);
                                                request_memory_writer.Write(":");
                                                request_memory_writer.Write(Port);
                                                request_memory_writer.Flush();
                                            }
                                            else
                                            {
                                                serializer.WriteObject(request_stream, CustomServerInfo);
                                            }
                                        }
                                        break;
                                    case EAnnouncerAPI.SACNRMonitorAPI:
                                        http_web_request.ContentType = "application/x-www-form-urlencoded";
                                        using (Stream request_stream = http_web_request.GetRequestStream())
                                        {
                                            StreamWriter request_memory_writer = new StreamWriter(request_stream);
                                            request_memory_writer.Write("ipp=");
                                            request_memory_writer.Write(IPv4Address);
                                            request_memory_writer.Write(":");
                                            request_memory_writer.Write(Port);
                                            request_memory_writer.Flush();
                                        }
                                        break;
                                }
                                try
                                {
                                    using (HttpWebResponse response = http_web_request.GetResponse() as HttpWebResponse)
                                    {
                                        r = response.StatusCode;
                                        Log("\"" + http_web_request.Address + "\" responded with \"" + r + "\"", false);
#if DEBUG
                                        using (Stream response_stream = response.GetResponseStream())
                                        {
                                            using (StreamReader response_reader = new StreamReader(response_stream))
                                            {
                                                Log(response_reader.ReadToEnd(), false);
                                            }
                                        }
#endif
                                    }
                                }
                                catch (WebException e)
                                {
                                    HttpWebResponse response = e.Response as HttpWebResponse;
                                    if (response != null)
                                    {
                                        r = response.StatusCode;
                                        if (r != HttpStatusCode.Found)
                                        {
                                            Log(e, true);
                                        }
                                        Log("\"" + http_web_request.Address + "\" responded with \"" + r + "\"", (r != HttpStatusCode.Redirect));
#if DEBUG
                                        using (Stream response_stream = response.GetResponseStream())
                                        {
                                            using (StreamReader response_reader = new StreamReader(response_stream))
                                            {
                                                Log(response_reader.ReadToEnd(), true);
                                            }
                                        }
#endif
                                    }
                                    else
                                    {
                                        Log(e, true);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log(e, true);
                }
                return r;
            });
            ret.Start();
            return ret;
        }

19 View Source File : HttpService.cs
License : The Unlicense
Project Creator : BuIlDaLiBlE

private async Task<WebHeaderCollection> GetContentInfo()
		{
			HttpWebRequest request = WebRequest.CreateHttp(_url);
			request.AllowAutoRedirect = true;
			request.KeepAlive = true;
			request.Method = "HEAD";
			request.UserAgent = App.UserAgent;

			using(WebResponse response = await request.GetResponseAsync())
			{
				return response.Headers;
			}
		}

19 View Source File : HttpService.cs
License : The Unlicense
Project Creator : BuIlDaLiBlE

internal async Task<byte[]> GetRange(ulong startBytes, ulong endBytes)
		{
			if(startBytes < endBytes)
			{
				HttpWebRequest request = WebRequest.CreateHttp(_url);
				request.AllowAutoRedirect = true;
				request.KeepAlive = true;
				request.AddRange((long)startBytes, (long)endBytes);
				request.Method = "GET";
				request.UserAgent = App.UserAgent;

				using(WebResponse response = await request.GetResponseAsync())
				{
					using(Stream responseStream = response.GetResponseStream())
					{
						using(MemoryStream output = new MemoryStream())
						{
							await responseStream.CopyToAsync(output);
							return output.ToArray();
						}
					}
				}
			}
			else
			{
				throw new Exception("Invalid byte range.");
			}
		}

19 View Source File : CopyHotkey.cs
License : GNU Affero General Public License v3.0
Project Creator : Caraxi

private void OpenTeamcraft(ExtendedItem extendedItem) {
            if (teamcraftLocalFailed || Config.TeamcraftLinkHotkeyForceBrowser) {
                Common.OpenBrowser($"https://ffxivteamcraft.com/db/en/item/{extendedItem.RowId}");
                return;
            }
            Task.Run(() => {
                try {
                    var wr = WebRequest.CreateHttp($"http://localhost:14500/db/en/item/{extendedItem.RowId}");
                    wr.Timeout = 500;
                    wr.Method = "GET";
                    wr.GetResponse().Close();
                } catch {
                    try {
                        if (System.IO.Directory.Exists(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ffxiv-teamcraft"))) {
                            Common.OpenBrowser($"teamcraft:///db/en/item/{extendedItem.RowId}");
                        } else {
                            teamcraftLocalFailed = true;
                            Common.OpenBrowser($"https://ffxivteamcraft.com/db/en/item/{extendedItem.RowId}");
                        }
                    } catch {
                        teamcraftLocalFailed = true;
                        Common.OpenBrowser($"https://ffxivteamcraft.com/db/en/item/{extendedItem.RowId}");
                    }
                }
            });
        }

19 View Source File : Utils.cs
License : GNU Affero General Public License v3.0
Project Creator : cc004

public static string SendGet(string url)
        {
            HttpWebRequest request = WebRequest.CreateHttp(url);
            request.Method = "GET";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
            var response = request.GetResponse();
            return Encoding.UTF8.GetString(response.ReadAll());
        }

19 View Source File : XboxMinecraftLogin.cs
License : MIT License
Project Creator : CmlLib

public AuthenticationResponse LoginWithXbox(string uhs, string xstsToken)
        {
            var url = "https://api.minecraftservices.com/authentication/login_with_xbox";
            var req = WebRequest.CreateHttp(url);
            req.ContentType = "application/json";
            req.Method = "POST";

            var reqBody = $"{{\"idenreplacedyToken\": \"XBL3.0 x={uhs};{xstsToken}\"}}";
            writeReq(req, reqBody);

            var res = req.GetResponse();
            var resBody = readRes(res);

            var obj = JsonConvert.DeserializeObject<AuthenticationResponse>(resBody);
            obj.ExpiresOn = DateTime.Now.AddSeconds(obj.ExpiresIn);
            return obj;
        }

19 View Source File : MojangAPI.cs
License : MIT License
Project Creator : CmlLib

public static UserProfile GetProfileUsingToken(string bearerToken)
        {
            var url = "https://api.minecraftservices.com/minecraft/profile";
            var req = WebRequest.CreateHttp(url);
            req.Method = "GET";
            req.Headers["Authorization"] = "Bearer " + bearerToken;

            var res = req.GetResponse();
            var resBody = readRes(res);
            var job = JObject.Parse(resBody);

            return new UserProfile
            {
                UUID = job["id"]?.ToString(),
                Name = job["name"]?.ToString(),
            };
        }

19 View Source File : WebDownload.cs
License : MIT License
Project Creator : CmlLib

internal void DownloadFile(string url, string path)
        {
            var req = WebRequest.CreateHttp(url); // Request
            var response = req.GetResponse();
            var filesize = long.Parse(response.Headers.Get("Content-Length") ?? "0"); // Get File Length

            var webStream = response.GetResponseStream(); // Get NetworkStream
            if (webStream == null)
                throw new NullReferenceException(nameof(webStream));
            
            var fileStream = File.Open(path, FileMode.Create); // Open FileStream

            var bufferSize = DefaultBufferSize; // Make buffer
            var buffer = new byte[bufferSize];
            int length;

            var fireEvent = filesize > DefaultBufferSize;
            var processedBytes = 0;

            while ((length = webStream.Read(buffer, 0, bufferSize)) > 0) // read to end and write file
            {
                fileStream.Write(buffer, 0, length);

                // raise event
                if (fireEvent)
                {
                    processedBytes += length;
                    progressChanged(processedBytes, filesize);
                }
            }

            webStream.Dispose(); // Close streams
            fileStream.Dispose();
        }

19 View Source File : WebDownload.cs
License : MIT License
Project Creator : CmlLib

internal void DownloadFileLimit(string url, string path)
        {
            string? directoryName = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(directoryName))
                Directory.CreateDirectory(directoryName);

            var req = WebRequest.CreateHttp(url);
            req.Method = "GET";
            req.Timeout = 5000;
            req.ReadWriteTimeout = 5000;
            req.ContinueTimeout = 5000;
            var res = req.GetResponse();

            using (var httpStream = res.GetResponseStream())
            using (var fs = File.OpenWrite(path))
            {
                httpStream.CopyTo(fs);
            }
        }

19 View Source File : MojangAPI.cs
License : MIT License
Project Creator : CmlLib

public static bool CheckGameOwnership(string bearerToken)
        {
            var url = "https://api.minecraftservices.com/enreplacedlements/mcstore";
            var req = WebRequest.CreateHttp(url);
            req.Method = "GET";
            req.Headers["Authorization"] = "Bearer " + bearerToken;

            var res = req.GetResponse();
            var resBody = readRes(res);

            var job = JObject.Parse(resBody);
            var itemsCount = (job["items"] as JArray)?.Count ?? 0;
            return itemsCount != 0;
        }

19 View Source File : WebDownload.cs
License : MIT License
Project Creator : CmlLib

public void DownloadFile(string url, string path)
        {
            var req = WebRequest.CreateHttp(url); // Request
            var response = req.GetResponse();
            var filesize = long.Parse(response.Headers.Get("Content-Length")); // Get File Length

            var webStream = response.GetResponseStream(); // Get NetworkStream
            var fileStream = File.Open(path, FileMode.Create); // Open FileStream

            var bufferSize = DefaultBufferSize; // Make buffer
            var buffer = new byte[bufferSize];
            var length = 0;

            var processedBytes = 0;

            while ((length = webStream.Read(buffer, 0, bufferSize)) > 0) // read to end and write file
            {
                fileStream.Write(buffer, 0, length);

                // raise event
                processedBytes += length;
                ProgressChanged(processedBytes, filesize);
            }

            buffer = null;
            webStream.Dispose(); // Close streams
            fileStream.Dispose();
        }

19 View Source File : MLogin.cs
License : MIT License
Project Creator : CmlLib

private HttpWebResponse mojangRequest(string endpoint, string postdata)
        {
            var http = WebRequest.CreateHttp("https://authserver.mojang.com/" + endpoint);
            http.ContentType = "application/json";
            http.Method = "POST";
            using (var req = new StreamWriter(http.GetRequestStream()))
            {
                req.Write(postdata);
                req.Flush();
            }

            var res = http.GetResponseNoException();
            return res;
        }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : cyotek

private HttpWebRequest CreateRequest(string method, string uri, string query)
    {
      HttpWebRequest request;

      if (!string.IsNullOrEmpty(query))
      {
        if (query[0] == '?')
        {
          uri += query;
        }
        else
        {
          uri += "?" + query;
        }
      }

#if NET20 || NET35 || NET40
      request = (HttpWebRequest)WebRequest.Create(uri);
#else
      request = WebRequest.CreateHttp(uri);
#endif
      request.Headers.Add("Authorization", _authorization);
      request.Accept = _jsonContentType;
      request.Method = method;

      return request;
    }

19 View Source File : CDNCache.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

private bool DownloadFile(string cdnPath, string path, int numRetries = 0)
        {
            if (numRetries >= 5)
                return false;

            string url = "http://" + _config.CDNHost + "/" + cdnPath;

            Directory.CreateDirectory(Path.GetDirectoryName(path));

            //using (var client = new HttpClient())
            //{
            //    var msg = client.GetAsync(url).Result;

            //    using (Stream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            //    {
            //        //CacheMetaData.AddToCache(resp, path);
            //        //CopyToStream(stream, fs, resp.ContentLength);

            //        msg.Content.CopyToAsync(fs).Wait();
            //    }
            //}

            DateTime startTime = DateTime.Now;

            //long fileSize = GetFileSize(cdnPath);

            //if (fileSize == -1)
            //    return false;

            HttpWebRequest req = WebRequest.CreateHttp(url);
            req.ReadWriteTimeout = 15000;

            //req.AddRange(0, fileSize - 1);

            HttpWebResponse resp;

            try
            {
                using (resp = (HttpWebResponse)req.GetResponse())
                using (Stream stream = resp.GetResponseStream())
                using (Stream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    stream.CopyToStream(fs, resp.ContentLength);
                    CacheFile(resp, Path.GetFileName(path));
                }
            }
            catch (WebException exc)
            {
                resp = (HttpWebResponse)exc.Response;

                if (exc.Status == WebExceptionStatus.ProtocolError && (resp.StatusCode == HttpStatusCode.NotFound || resp.StatusCode == (HttpStatusCode)429))
                    return DownloadFile(cdnPath, path, numRetries + 1);
                else
                    return false;
            }

            TimeSpan timeSpent = DateTime.Now - startTime;
            CDNCacheStats.timeSpentDownloading += timeSpent;
            CDNCacheStats.numFilesDownloaded++;

            return true;
        }

19 View Source File : CDNCache.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

private long GetFileSize(string cdnPath, int numRetries = 0)
        {
            if (numRetries >= 5)
                return -1;

            string url = "http://" + _config.CDNHost + "/" + cdnPath;

            HttpWebRequest req = WebRequest.CreateHttp(url);
            req.Method = "HEAD";

            HttpWebResponse resp;

            try
            {
                using (resp = (HttpWebResponse)req.GetResponse())
                {
                    return resp.ContentLength;
                }
            }
            catch (WebException exc)
            {
                resp = (HttpWebResponse)exc.Response;

                if (exc.Status == WebExceptionStatus.ProtocolError && (resp.StatusCode == HttpStatusCode.NotFound || resp.StatusCode == (HttpStatusCode)429))
                    return GetFileSize(cdnPath, numRetries + 1);
                else
                    return -1;
            }
        }

19 View Source File : CDNCache.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

private CacheMetaData GetMetaData(string cdnPath, string fileName, int numRetries = 0)
        {
            if (numRetries >= 5)
                return null;

            string url = "http://" + _config.CDNHost + "/" + cdnPath;

            HttpWebRequest req = WebRequest.CreateHttp(url);
            req.Method = "HEAD";

            HttpWebResponse resp;

            try
            {
                using (resp = (HttpWebResponse)req.GetResponse())
                {
                    return CacheFile(resp, fileName);
                }
            }
            catch (WebException exc)
            {
                resp = (HttpWebResponse)exc.Response;

                if (exc.Status == WebExceptionStatus.ProtocolError && (resp.StatusCode == HttpStatusCode.NotFound || resp.StatusCode == (HttpStatusCode)429))
                    return GetMetaData(cdnPath, fileName, numRetries + 1);
                else
                    return null;
            }
        }

19 View Source File : CDNIndexHandler.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

public Stream OpenDataFile(IndexEntry entry, int numRetries = 0)
        {
            var archive = config.Archives[entry.Index];

            string file = config.CDNPath + "/data/" + archive.Substring(0, 2) + "/" + archive.Substring(2, 2) + "/" + archive;

            if (numRetries >= 5)
                return null;

            Stream stream = CDNCache.Instance.OpenFile(file, true);

            if (stream != null)
            {
                stream.Position = entry.Offset;
                MemoryStream ms = new(entry.Size);
                stream.CopyBytes(ms, entry.Size);
                ms.Position = 0;
                return ms;
            }

            //using (HttpClient client = new HttpClient())
            //{
            //    client.DefaultRequestHeaders.Range = new RangeHeaderValue(entry.Offset, entry.Offset + entry.Size - 1);

            //    var resp = client.GetStreamAsync(url).Result;

            //    MemoryStream ms = new MemoryStream(entry.Size);
            //    resp.CopyBytes(ms, entry.Size);
            //    ms.Position = 0;
            //    return ms;
            //}

            string url = "http://" + config.CDNHost + "/" + file;

            HttpWebRequest req = WebRequest.CreateHttp(url);
            req.ReadWriteTimeout = 15000;
            //req.Headers[HttpRequestHeader.Range] = string.Format("bytes={0}-{1}", entry.Offset, entry.Offset + entry.Size - 1);
            req.AddRange(entry.Offset, entry.Offset + entry.Size - 1);

            HttpWebResponse resp;

            try
            {
                using (resp = (HttpWebResponse)req.GetResponse())
                using (Stream rstream = resp.GetResponseStream())
                {
                    MemoryStream ms = new(entry.Size);
                    rstream.CopyBytes(ms, entry.Size);
                    ms.Position = 0;
                    return ms;
                }
            }
            catch (WebException exc)
            {
                resp = (HttpWebResponse)exc.Response;

                if (exc.Status == WebExceptionStatus.ProtocolError && (resp.StatusCode == HttpStatusCode.NotFound || resp.StatusCode == (HttpStatusCode)429))
                    return OpenDataFile(entry, numRetries + 1);
                else
                    return null;
            }
        }

19 View Source File : CDNIndexHandler.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

public static Stream OpenFileDirect(string url)
        {
            //using (HttpClient client = new HttpClient())
            //{
            //    var resp = client.GetStreamAsync(url).Result;

            //    MemoryStream ms = new MemoryStream();
            //    resp.CopyTo(ms);
            //    ms.Position = 0;
            //    return ms;
            //}

            HttpWebRequest req = WebRequest.CreateHttp(url);
            //long fileSize = GetFileSize(url);
            //req.AddRange(0, fileSize - 1);
            using HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            using Stream stream = resp.GetResponseStream();
            MemoryStream ms = new();
            stream.CopyToStream(ms, resp.ContentLength);
            ms.Position = 0;
            return ms;
        }

See More Examples