System.Net.WebHeaderCollection.Add(string, string)

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

597 Examples 7

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void GetFileContent(string paylocation, string droploc, string fname, string dtype)
        {
            bool uricheck = Uri.IsWellFormedUriString(paylocation, UriKind.RelativeOrAbsolute);
            if (paylocation == "local")
            {
                String plfile = "LOADLOADLOAD";
                if(dtype == "flat")
                {
                    String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                    vbsp = vbsp.Insert(0, finalpay);
                }
                else if (dtype == "nonflat")
                {
                    datavals = plfile;
                }
            }
            else
            {
                if (uricheck)
                {
                    try
                    {
                        WebClient webcl = new WebClient();
                        //May want to change this
                        webcl.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
                        byte[] filedata = webcl.DownloadData(paylocation);
                        string plfile = Convert.ToBase64String(filedata);
                        if (dtype == "flat")
                        {
                            String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                            vbsp = vbsp.Insert(0, finalpay);
                        }
                        else if (dtype == "nonflat")
                        {
                            datavals = plfile;
                        }
                    }
                    catch (WebException)
                    {
                        Console.WriteLine("[X] URL doesnt exist");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        Byte[] plbytes = File.ReadAllBytes(paylocation);
                        String plfile = Convert.ToBase64String(plbytes);
                        if(dtype == "flat")
                        {
                            String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                            vbsp = vbsp.Insert(0, finalpay);
                        }
                        else if (dtype == "nonflat")
                        {
                            datavals = plfile;
                        }
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("[X] File doesnt exist");
                        return;
                    }
                }
            }
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

void EndResponse(IAsyncResult ar)
        {
            StateObject state = ar.AsyncState as StateObject;
            try
            {
                HttpWebResponse webResponse = state.HttpWebRequest.EndGetResponse(ar) as HttpWebResponse;
                state.ResponseInfo.StatusCode = webResponse.StatusCode;
                state.ResponseInfo.Headers = new WebHeaderCollection();
                foreach (string key in webResponse.Headers.AllKeys)
                {
                    state.ResponseInfo.Headers.Add(key, webResponse.Headers[key]);
                }
                state.ReadStream = webResponse.GetResponseStream();
                state.ReadStream.BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallBack, state);
            }
            catch (Exception ex)
            {
                HandException(ex, state);
            }
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

private void InitWebRequest(RequestInfo info, Action<ResponseInfo> act, out HttpWebRequest webRequest, out StateObject state)
        {

            webRequest = HttpWebRequest.CreateDefault(new Uri(info.Url)) as HttpWebRequest;
            webRequest.KeepAlive = true;
            webRequest.Timeout = 20 * 1000;
            webRequest.AllowAutoRedirect = info.AllowAutoRedirect;
            if (info.Headers != null && info.Headers.Count > 0)
            {
                foreach (string key in info.Headers.Keys)
                {
                    webRequest.Headers.Add(key, info.Headers[key]);
                }
            }
            //webRequest.Proxy = WebProxy.GetDefaultProxy();
            //webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;  
            //webResponse.Headers.Get("Set-Cookie");
            state = new StateObject
            {
                Buffer = new byte[1024 * 1024],
                HttpWebRequest = webRequest,
                Action = act,
                ResponseInfo = new ResponseInfo
                {
                    RequestInfo = info,
                    ResponseContent = new MemoryStream()
                }
            };
        }

19 View Source File : Send_0x0002.cs
License : MIT License
Project Creator : 499116344

public void HttpUpLoadGroupImg(long groupNum, string ukey, string fileName)
        {
            using (var webclient = new WebClient())
            {
                var file = new FileStream(fileName, FileMode.Open);
                var apiUrl =
                    $"http://htdata2.qq.com/cgi-bin/httpconn?htcmd=0x6ff0071&ver=5515&term=pc&ukey={ukey}&filesize={file.Length}&range=0&uin{User.QQ}&&groupcode={groupNum}";
                webclient.Headers["User-Agent"] = "QQClient";
                webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                var result = webclient.UploadData(apiUrl,
                    file.ToBytesArray());

                Console.Write(Encoding.UTF8.GetString(result));
            }
        }

19 View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635

private void SetRequest(HttpItem item)
        {
            // 验证证书
            SetCer(item);
            if (item.IPEndPoint != null)
            {
                _IPEndPoint = item.IPEndPoint;
                //设置本地的出口ip和端口
                request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
            }
            //设置Header参数
            if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys)
                {
                    request.Headers.Add(key, item.Header[key]);
                }
            // 设置代理
            SetProxy(item);
            if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
            request.ServicePoint.Expect100Continue = item.Expect100Continue;
            //请求方式Get或者Post
            request.Method = item.Method;
            request.Timeout = item.Timeout;
            request.KeepAlive = item.KeepAlive;
            request.ReadWriteTimeout = item.ReadWriteTimeout;
            if (!string.IsNullOrWhiteSpace(item.Host))
            {
                request.Host = item.Host;
            }
            if (item.IfModifiedSince != null) request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince);
            //Accept
            request.Accept = item.Accept;
            //ContentType返回类型
            request.ContentType = item.ContentType;
            //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
            request.UserAgent = item.UserAgent;
            // 编码
            encoding = item.Encoding;
            //设置安全凭证
            request.Credentials = item.ICredentials;
            //设置Cookie
            SetCookie(item);
            //来源地址
            request.Referer = item.Referer;
            //是否执行跳转功能
            request.AllowAutoRedirect = item.Allowautoredirect;
            if (item.MaximumAutomaticRedirections > 0)
            {
                request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections;
            }
            //设置Post数据
            SetPostData(item);
            //设置最大连接
            if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
        }

19 View Source File : SoapSearch.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

private HttpWebRequest BuildRequest(string soapMessage, string soapAction) {
         HttpWebRequest Request;
         Request = (HttpWebRequest)WebRequest.Create(AppSettings.SearchUrl(this.Style));
         try {
            Request.Timeout = int.Parse(AppSettings.RequestTimeoutInMilliseconds, CultureInfo.CurrentCulture);
         }
         catch {
            Request.Timeout = 100000;
         }
         Request.Headers.Add("SoapAction", soapAction);
         Request.ContentType = "text/xml; charset=utf-8";
         Request.ContentLength = soapMessage.Length;
         Request.Proxy = GetWebProxy();
         Request.Method = "POST";
         return (Request);
      }

19 View Source File : ClientFactory.cs
License : MIT License
Project Creator : Adoxio

protected virtual void UpdateWebRequest(SharePointConnection connection, WebRequest request)
		{
			if (connection.RequestTimeout != null) request.Timeout = connection.RequestTimeout.Value;

			var httpRequest = request as HttpWebRequest;

			if (httpRequest == null) return;

			if (IsOnline(connection))
			{
				UpdateHttpWebRequestForOnline(connection, httpRequest);
			}
			else
			{
				httpRequest.Credentials = connection.Credentials;

				// if this context is using default Windows authentication add a WebRequest Header to stop forms auth from potentially interfering.
				if (connection.AuthenticationMode.GetValueOrDefault() == ClientAuthenticationMode.Default)
				{
					httpRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
				}
			}
		}

19 View Source File : JsonDownloader.cs
License : MIT License
Project Creator : adrianmteo

public async Task<T> GetObject<T>(string url)
        {
            Client.Headers.Add("Content-Type", "application/json");

            string json = await Client.DownloadStringTaskAsync(url);

            return JsonConvert.DeserializeObject<T>(json);
        }

19 View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen

public HttpWebRequest GetHttpWebRequest(string endpoint, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
        {
            //Add default headers
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Accept-Charset", "UTF-8");
            httpWebRequest.Headers.Add("Cache-Control", "no-cache");
            httpWebRequest.UserAgent = $"{config.ApplicationName} {ClientConfig.UserAgentSuffix}{ClientConfig.LibVersion}";
            if (!string.IsNullOrWhiteSpace(requestOptions?.IdempotencyKey))
            {
                httpWebRequest.Headers.Add("Idempotency-Key", requestOptions?.IdempotencyKey);
            }
            //Use one of two authentication method.
            if (isApiKeyRequired || !string.IsNullOrEmpty(config.XApiKey))
            {
                httpWebRequest.Headers.Add("x-api-key", config.XApiKey);
            }
            else if (!string.IsNullOrEmpty(config.Preplacedword))
            {
                var authString = config.Username + ":" + config.Preplacedword;
                var bytes = Encoding.UTF8.GetBytes(authString);
                var credentials = Convert.ToBase64String(bytes);
                httpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
                httpWebRequest.UseDefaultCredentials = true;
            }
            if (config.Proxy != null)
            {
                httpWebRequest.Proxy = config.Proxy;
            }
            httpWebRequest.ServerCertificateValidationCallback = ServerCertificateValidationCallback;
            return httpWebRequest;
        }

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 : BitMaxProClient.cs
License : Apache License 2.0
Project Creator : AlexWan

private string GetData(string apiPath, bool auth = false, string accGroup = null, string jsonContent = null,
            string orderId = null, string time = null, Method method = Method.GET, bool need = false)
        {
            lock (_queryLocker)
            {
                try
                {
                    Uri uri;

                    HttpWebRequest httpWebRequest;

                    if (!auth)
                    {
                        uri = new Uri(_baseUrl + "api/pro/v1/" + apiPath);

                        httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                    }
                    else
                    {
                        if (accGroup == null)
                        {
                            uri = new Uri(_baseUrl + "api/pro/v1/" + apiPath);
                        }
                        else
                        {
                            var str = _baseUrl + accGroup + "/" + "api/pro/v1/" + apiPath;

                            if (need)
                            {
                                str += "?n=10&executedOnly=True";
                            }

                            uri = new Uri(str);
                        }

                        string timestamp;

                        if (time == null)
                        {
                            timestamp = TimeManager.GetUnixTimeStampMilliseconds().ToString();
                        }
                        else
                        {
                            timestamp = time;
                        }

                        string signatureMsg;

                        if (orderId == null)
                        {
                            signatureMsg = timestamp + "+" + apiPath;
                        }
                        else
                        {
                            //signatureMsg = timestamp + "+" + apiPath + "+" + orderId;
                            signatureMsg = timestamp + "+" + "order";
                        }

                        if (signatureMsg.EndsWith("cash/balance"))
                        {
                            signatureMsg = signatureMsg.Replace("cash/", "");
                            //signatureMsg = signatureMsg.Remove(signatureMsg.Length - 11, 4);
                        }

                        if (signatureMsg.EndsWith("margin/balance"))
                        {
                            signatureMsg = signatureMsg.Replace("margin/", "");
                            //signatureMsg = signatureMsg.Remove(signatureMsg.Length - 13, 6);
                        }


                        var codedSignature = CreateSignature(signatureMsg);

                        httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

                        httpWebRequest.Headers.Add("x-auth-key", _apiKey);
                        httpWebRequest.Headers.Add("x-auth-signature", codedSignature);
                        httpWebRequest.Headers.Add("x-auth-timestamp", timestamp.ToString());

                        if (orderId != null)
                        {
                            httpWebRequest.Headers.Add("x-auth-coid", orderId);
                        }
                    }

                    httpWebRequest.Method = method.ToString();

                    if (jsonContent != null)
                    {
                        var data = Encoding.UTF8.GetBytes(jsonContent);

                        httpWebRequest.ContentType = "application/json";

                        httpWebRequest.ContentLength = data.Length;

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

                    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                    string responseMsg;

                    using (var stream = httpWebResponse.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                        {
                            responseMsg = reader.ReadToEnd();
                        }
                    }

                    httpWebResponse.Close();

                    return responseMsg;
                }
                catch (InvalidOperationException invalidOperationException)
                {
                    SendLogMessage("Failed to get stream to read response from server..   " + invalidOperationException.Message, LogMessageType.Error);
                    return null;
                }
                catch (Exception exception)
                {
                    SendLogMessage(exception.Message, LogMessageType.Error);
                    return null;
                }
            }
        }

19 View Source File : ExmoClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public string ApiQuery(string apiName, IDictionary<string, string> req, string tradeCouples = null,
            int? limit = null)
        {
            try
            {
                lock (_queryHttpLocker)
                {
                    _rateGate.WaitToProceed();

                    using (var wb = new WebClient())
                    {
                        req.Add("nonce", Convert.ToString(_nounce++));

                        if (limit != null)
                        {
                            req.Add("limit", limit.ToString());
                        }

                        if (tradeCouples != null)
                        {
                            req.Add("pair", tradeCouples);
                        }

                        var message = ToQueryString(req);



                        var sign = Sign(_secret, message);

                        wb.Headers.Add("Sign", sign);
                        wb.Headers.Add("Key", _key);

                        var data = req.ToNameValueCollection();
                        //var response = wb.UploadValues(string.Format(_url, apiName), "POST", data);
                        byte[] response;

                        response = wb.UploadValues(_url + apiName + "//", "POST", data);
                        return Encoding.UTF8.GetString(response);
                    }
                }
            }
            catch (Exception e)
            {
                SendLogMessage(e.ToString(), LogMessageType.Error);

                IsConnected = false;

                if (Disconnected != null)
                {
                    Disconnected();
                }

                return "";
            }
        }

19 View Source File : BitMexClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public string CreateQuery(string method, string function, Dictionary<string, string> param = null, bool auth = false)
        {
            lock (_queryHttpLocker)
            {
                //Wait for RateGate
                _rateGate.WaitToProceed();

                string paramData = BuildQueryData(param);
                string url = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
                string postData = (method != "GET") ? paramData : "";

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_domain + url);
                webRequest.Method = method;

                if (auth)
                {
                    string nonce = GetNonce().ToString();
                    string message = method + url + nonce + postData;
                    byte[] signatureBytes = Hmacsha256(Encoding.UTF8.GetBytes(_secKey), Encoding.UTF8.GetBytes(message));
                    string signatureString = ByteArrayToString(signatureBytes);

                    webRequest.Headers.Add("api-nonce", nonce);
                    webRequest.Headers.Add("api-key", _id);
                    webRequest.Headers.Add("api-signature", signatureString);
                }

                try
                {
                    if (postData != "")
                    {
                        webRequest.ContentType = "application/x-www-form-urlencoded";
                        var data = Encoding.UTF8.GetBytes(postData);
                        using (var stream = webRequest.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }
                    }

                    using (WebResponse webResponse = webRequest.GetResponse())
                    using (Stream str = webResponse.GetResponseStream())
                    using (StreamReader sr = new StreamReader(str))
                    {
                        return sr.ReadToEnd();
                    }
                }
                catch (WebException wex)
                {
                    using (HttpWebResponse response = (HttpWebResponse)wex.Response)
                    {
                        if (response == null)
                            throw;

                        using (Stream str = response.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(str))
                            {
                                string error = sr.ReadToEnd();

                                if (ErrorEvent != null)
                                {
                                    ErrorEvent(error);
                                }
                                return sr.ReadToEnd();
                            }
                        }
                    }
                }
            }
        }

19 View Source File : RestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan

public string SendGetQuery(string method, string baseUri, string endPoint, Dictionary<string, string> headers)
        {
            Uri uri = new Uri(baseUri + endPoint);

            if (uri.ToString().Contains("?"))
            {
                var t = 6;
            }

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Method = method;

            httpWebRequest.Accept = "application/json";
            httpWebRequest.ContentType = "application/json";

            foreach (var header in headers)
            {
                httpWebRequest.Headers.Add(header.Key, header.Value);
            }

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            string responseMsg;

            using (var stream = httpWebResponse.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                {
                    responseMsg = reader.ReadToEnd();
                }
            }

            httpWebResponse.Close();

            if (httpWebResponse.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("Failed request " + responseMsg);
            }

            return responseMsg;
        }

19 View Source File : RestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan

public string SendPostQuery(string method, string url, string endPoint, byte[] data, Dictionary<string, string> headers)
        {
            Uri uri = new Uri(url + endPoint);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Method = method;

            httpWebRequest.Accept = "application/json";
            httpWebRequest.ContentType = "application/json";



            foreach (var header in headers)
            {
                httpWebRequest.Headers.Add(header.Key, header.Value);
            }

            httpWebRequest.ContentLength = data.Length;

            using (Stream reqStream = httpWebRequest.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }

            string responseMsg;

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var stream = httpWebResponse.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                {
                    responseMsg = reader.ReadToEnd();
                }
            }
            return responseMsg;
        }

19 View Source File : KrakenRestApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private JsonObject QueryPrivate(string a_sMethod, string props = null)
        {
            // generate a 64 bit nonce using a timestamp at tick resolution
            Int64 nonce = DateTime.Now.Ticks;
            props = "nonce=" + nonce + props;

            string path = string.Format("/{0}/private/{1}", _version, a_sMethod);
            string address = _url + path;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(address);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            webRequest.Headers.Add("API-Key", _key);
            
            byte[] base64DecodedSecred = Convert.FromBase64String(_secret);

            var np = nonce + Convert.ToChar(0) + props;

            var pathBytes = Encoding.UTF8.GetBytes(path);
            var hash256Bytes = sha256_hash(np);
            var z = new byte[pathBytes.Count() + hash256Bytes.Count()];
            pathBytes.CopyTo(z, 0);
            hash256Bytes.CopyTo(z, pathBytes.Count());

            var signature = getHash(base64DecodedSecred, z);

            webRequest.Headers.Add("API-Sign", Convert.ToBase64String(signature));


            if (props != null)
            {
                using (var writer = new StreamWriter(webRequest.GetRequestStream()))
                {
                    writer.Write(props);
                }
            }

            //Make the request
            try
            {
                //Wait for RateGate
                _rateGate.WaitToProceed();
                //Thread.Sleep(2000);

                using (WebResponse webResponse = webRequest.GetResponse())
                {
                    using (Stream str = webResponse.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(str))
                        {
                            return (JsonObject)JsonConvert.Import(sr);
                        }
                    }
                }
            }
            catch (WebException wex)
            {
                using (HttpWebResponse response = (HttpWebResponse)wex.Response)
                {
                    using (Stream str = response.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(str))
                        {
                            if (response.StatusCode != HttpStatusCode.InternalServerError)
                            {
                                throw;
                            }
                            return (JsonObject)JsonConvert.Import(sr);
                        }
                    }
                }

            }
        }

19 View Source File : RestChannel.cs
License : Apache License 2.0
Project Creator : AlexWan

public string SendPostQuery(string url, string endPoint, byte[] data, Dictionary<string, string> headers)
        {
            Uri uri = new Uri(url + endPoint);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Method = "post";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";

            foreach (var header in headers)
            {
                httpWebRequest.Headers.Add(header.Key, header.Value);
            }
            
            httpWebRequest.ContentLength = data.Length;

            using (Stream reqStream = httpWebRequest.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }

            string responseMsg;

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var stream = httpWebResponse.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                {
                    responseMsg = reader.ReadToEnd();
                }
            }
            return responseMsg;
        }

19 View Source File : TinkoffClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public string ApiQuery(string url, string type, IDictionary<string, string> req)
        {
            try
            {
                lock (_queryLocker)
                {
                    _rateGate.WaitToProceed();

                    using (var wb = new WebClient())
                    {
                        wb.Headers.Add("Authorization", "Bearer " + _token);

                        byte[] response;

                        if (type == "POST" && req.Count != 0)
                        {
                            string str = "{";
                            bool isFirst = true;

                            foreach (var r in req)
                            {
                                if (isFirst == false)
                                {
                                    str += ",";
                                }

                                isFirst = false;

                                str += "\"" + r.Key + "\":";

                                try
                                {
                                    r.Value.ToDecimal();
                                    str += r.Value.Replace(",", ".");
                                }
                                catch
                                {
                                    str += "\"" + r.Value + "\"";
                                }
                            }
                            str += "}";

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

                            //MessageBox.Show(str);
                            response = wb.UploadData(url, type, postData);
                        }
                        else // if(type == "GET")
                        {
                            response = wb.DownloadData(url);
                        }

                        return Encoding.UTF8.GetString(response);
                    }
                }
            }
            catch (Exception error)
            {
                // MessageBox.Show(error.ToString());
                return null;
            }
        }

19 View Source File : main.cs
License : GNU General Public License v3.0
Project Creator : ALIILAPRO

private void mtd(object Proxiess)
        {
            bool start = this._start;

            if (start)
            {
                try
                {
                    string host = Proxiess.ToString().Split(new char[]
                              {
                        ':'
                              })[0];
                    string value = Proxiess.ToString().Split(new char[]
                    {
                        ':'
                    })[1];
                    WebProxy proxy = new WebProxy(host, Convert.ToInt32(value));
                    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.cloudflareclient.com/v0a745/reg");
                    httpWebRequest.ContentType = "application/json";
                    httpWebRequest.Method = "POST";
                    httpWebRequest.Headers.Add("Accept-Encoding", "gzip");
                    httpWebRequest.ContentType = "application/json; charset=UTF-8";
                    httpWebRequest.Host = "api.cloudflareclient.com";
                    httpWebRequest.KeepAlive = true;
                    httpWebRequest.UserAgent = "okhttp/3.12.1";
                    httpWebRequest.Proxy = proxy;
                    string install_id = this.GenerateUniqCode(22);
                    string key        = this.GenerateUniqCode(43) + "=";
                    string tos        = DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fff") + "+07:00";
                    string fcm_token  = install_id + ":APA91b" + this.GenerateUniqCode(134);
                    string referer    = this.txtid.Text;
                    string type       = "Android";
                    string locale     = "en-GB";
                    var body = new
                    {
                        install_id = install_id,
                        key = key,
                        tos = tos,
                        fcm_token = fcm_token,
                        referrer = referer,
                        warp_enabled = false,
                        type = type,
                        locale = locale
                    };
                    string jsonBody = JsonConvert.SerializeObject(body);
                    using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        sw.Write(jsonBody);
                    }
                    HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (StreamReader sw = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        string result = sw.ReadToEnd();
                    }
                    httpResponse = null;
                    this._test++;
                    this._send++;
                    this.lblgood.Text = this._send.ToString();
                    this.lbltest.Text = this._test.ToString();
                    this.lblgb.Text = lblgood.Text + " GB Successfully added to your account.";
                }
                catch
                {
                    this._test++;
                    this._error++;
                    this.lblbad.Text = this._error.ToString();
                    this.lbltest.Text = this._test.ToString();
                }

            }
        }

19 View Source File : WebUtils.cs
License : Apache License 2.0
Project Creator : alipay

public HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "Aop4Net";
            req.Timeout = this.Timeout;
            req.ReadWriteTimeout = this.ReadWriteTimeout;

            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }

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

            return req;
        }

19 View Source File : NetMidiDownload.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static string DownloadMidi(string id)
        {



                try
                {
                    var request = (HttpWebRequest)WebRequest.Create(url+id);
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                    var response = (HttpWebResponse)request.GetResponse();
                using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        var responseString = reader.ReadToEnd();
                        return responseString;

                    }
                }
                
                    
                }
                catch (Exception e)
                {

                    Debug.WriteLine(e);
                    throw e;
                }



            
        }

19 View Source File : WebUtil.cs
License : MIT License
Project Creator : AmazingDM

public static HttpWebRequest CreateRequest(string url, int? timeout = null, string userAgent = null)
        {
            var req = (HttpWebRequest) WebRequest.Create(url);
            req.UserAgent = string.IsNullOrEmpty(userAgent) ? DefaultUserAgent : userAgent;
            req.Accept = "*/*";
            req.KeepAlive = true;
            req.Timeout = timeout ?? DefaultGetTimeout;
            req.ReadWriteTimeout = timeout ?? DefaultGetTimeout;
            req.Headers.Add("Accept-Charset", "utf-8");
            return req;
        }

19 View Source File : Response.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public static Response Get(ResourceRef res, NameValueCollection param = null, AccessToken token = null, string responseType = "application/json", Response previous = null, CancellationToken ct = default)
        {
            // Create request.
            var request = WebRequest.Create(res.Uri);
            request.CachePolicy = CachePolicy;
            request.Proxy = null;
            if (token != null)
                token.AddToRequest(request);
            if (request is HttpWebRequest httpRequest)
            {
                httpRequest.UserAgent = UserAgent;
                httpRequest.Accept = responseType;
                if (previous != null && param != null)
                {
                    httpRequest.IfModifiedSince = previous.Timestamp;

                    if (previous.ETag != null)
                        httpRequest.Headers.Add("If-None-Match", previous.ETag);
                }
            }

            if (param != null)
            {
                // Send data.
                UTF8Encoding utf8 = new UTF8Encoding();
                var binBody = Encoding.ASCII.GetBytes(string.Join("&", param.Cast<string>().Select(e => string.Format("{0}={1}", HttpUtility.UrlEncode(e, utf8), HttpUtility.UrlEncode(param[e], utf8)))));
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = binBody.Length;
                try
                {
                    using (var requestStream = request.GetRequestStream())
                        requestStream.Write(binBody, 0, binBody.Length, ct);
                }
                catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorUploading, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
            }

            ct.ThrowIfCancellationRequested();

            // Wait for data to start comming in.
            WebResponse response;
            try { response = request.GetResponse(); }
            catch (WebException ex)
            {
                // When the content was not modified, return the previous one.
                if (ex.Response is HttpWebResponse httpResponse)
                {
                    if (httpResponse.StatusCode == HttpStatusCode.NotModified)
                    {
                        previous.IsFresh = false;
                        return previous;
                    }

                    throw new WebExceptionEx(ex, ct);
                }

                throw new AggregateException(Resources.Strings.ErrorDownloading, ex);
            }

            ct.ThrowIfCancellationRequested();

            using (response)
            {
                // Read the data.
                var data = new byte[0];
                using (var stream = response.GetResponseStream())
                {
                    var buffer = new byte[1048576];
                    for (; ; )
                    {
                        // Read data chunk.
                        var count = stream.Read(buffer, 0, buffer.Length, ct);
                        if (count == 0)
                            break;

                        // Append it to the data.
                        var newData = new byte[data.LongLength + count];
                        Array.Copy(data, newData, data.LongLength);
                        Array.Copy(buffer, 0, newData, data.LongLength, count);
                        data = newData;
                    }
                }

                if (res.PublicKeys != null)
                {
                    // Generate signature URI.
                    var uriBuilderSig = new UriBuilder(res.Uri);
                    uriBuilderSig.Path += ".minisig";

                    // Create signature request.
                    request = WebRequest.Create(uriBuilderSig.Uri);
                    request.CachePolicy = CachePolicy;
                    request.Proxy = null;
                    if (token != null)
                        token.AddToRequest(request);
                    if (request is HttpWebRequest httpRequestSig)
                    {
                        httpRequestSig.UserAgent = UserAgent;
                        httpRequestSig.Accept = "text/plain";
                    }

                    // Read the Minisign signature.
                    byte[] signature = null;
                    try
                    {
                        using (var responseSig = request.GetResponse())
                        using (var streamSig = responseSig.GetResponseStream())
                        {
                            ct.ThrowIfCancellationRequested();

                            using (var readerSig = new StreamReader(streamSig))
                            {
                                foreach (var l in readerSig.ReadToEnd(ct).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    if (l.Trim().StartsWith($"untrusted comment:"))
                                        continue;
                                    signature = Convert.FromBase64String(l);
                                    break;
                                }
                                if (signature == null)
                                    throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
                            }
                        }
                    }
                    catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorDownloadingSignature, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }

                    ct.ThrowIfCancellationRequested();

                    // Verify Minisign signature.
                    using (var s = new MemoryStream(signature, false))
                    using (var r = new BinaryReader(s))
                    {
                        if (r.ReadChar() != 'E')
                            throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
                        byte[] payload;
                        switch (r.ReadChar())
                        {
                            case 'd': // PureEdDSA
                                payload = data;
                                break;

                            case 'D': // HashedEdDSA
                                payload = new eduEd25519.BLAKE2b(512).ComputeHash(data);
                                break;

                            default:
                                throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
                        }
                        ulong keyId = r.ReadUInt64();
                        if (!res.PublicKeys.ContainsKey(keyId))
                            throw new SecurityException(Resources.Strings.ErrorUntrustedMinisignPublicKey);
                        var sig = new byte[64];
                        if (r.Read(sig, 0, 64) != 64)
                            throw new ArgumentException(Resources.Strings.ErrorInvalidMinisignSignature);
                        using (eduEd25519.ED25519 key = new eduEd25519.ED25519(res.PublicKeys[keyId]))
                            if (!key.VerifyDetached(payload, sig))
                                throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
                    }
                }

                return
                    response is HttpWebResponse webResponse ?
                    new Response()
                    {
                        Value = Encoding.UTF8.GetString(data),
                        Timestamp = DateTime.TryParse(webResponse.GetResponseHeader("Last-Modified"), out var timestamp) ? timestamp : default,
                        ETag = webResponse.GetResponseHeader("ETag"),
                        IsFresh = true
                    } :
                    new Response()
                    {
                        Value = Encoding.UTF8.GetString(data),
                        IsFresh = true
                    };
            }
        }

19 View Source File : Main.cs
License : GNU Lesser General Public License v3.0
Project Creator : andisturber

public static Location getLocation(string url)
        {
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            string URL = url;
            System.Net.WebClient myWebClient = new System.Net.WebClient();
            myWebClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)");
            byte[] myDataBuffer = myWebClient.DownloadData(URL);
            string SourceCode = Encoding.GetEncoding("utf-8").GetString(myDataBuffer);
            Debug.WriteLine("返回值:" + SourceCode);
            Location Location = new Location();
            var rb = JObject.Parse(SourceCode);
            var result = JObject.Parse(rb["result"].ToString().Replace("[", "").Replace("]", ""));
            Location.Lareplacedude = Convert.ToDouble(result["lat"].ToString());
            Location.Longitude = Convert.ToDouble(result["lng"].ToString());
            Debug.WriteLine("经度:" + result["lat"].ToString());

            return Location;
        }

19 View Source File : VersionChecker.cs
License : MIT License
Project Creator : andruzzzhka

public static void CheckForUpdates()
        {
            try
            {
                using (var client = new WebClient())
                {
                    client.Headers.Add("user-agent", $"{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Name}/{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version}");

                    client.DownloadStringCompleted += Client_DownloadStringCompleted;
                    client.DownloadStringAsync(new Uri(releasesURL));
                }
            }
            catch (Exception e)
            {
                Logger.Instance.Warning($"Unable to check for updates! Exception: {e}");
            }
        }

19 View Source File : BeatSaver.cs
License : MIT License
Project Creator : andruzzzhka

public static async Task<SongInfo> GetRandomSong()
        {
            using (WebClient w = new WebClient())
            {
                w.Headers.Add("user-agent", $"{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Name}/{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version}");

                Random rand = new Random();
                int maxId = 11000;
                try
                {
                    string response = await w.DownloadStringTaskAsync($"{BeatSaverAPI}/latest");
                    JsonResponseSearch json = JsonConvert.DeserializeObject<JsonResponseSearch>(response);
                    if (json.Songs.Length > 0)
                    {
                        maxId = Convert.ToInt32(json.Songs[0].Key, 16);
                    }

                    bool found = false;
                    do {
                        try
                        {
                            response = await w.DownloadStringTaskAsync($"{BeatSaverAPI}/detail/{rand.Next(1, maxId).ToString("x")}");
                            found = true;
                        }
                        catch (WebException wex)
                        {
                            if (((HttpWebResponse)wex.Response).StatusCode != HttpStatusCode.NotFound)
                            {
                                throw;
                            }
                        }
                    } while (!found);

                    Song jsonSong = JsonConvert.DeserializeObject<Song>(response);
                    return new SongInfo() { levelId = jsonSong.Hash.ToUpper(), songName = jsonSong.Name, key = jsonSong.Key };  
                }
                catch (Exception e)
                {
#if DEBUG
                    Logger.Instance.Exception(e);
#endif
                    return null;
                }
            }
        }

19 View Source File : BeatSaver.cs
License : MIT License
Project Creator : andruzzzhka

public static async Task<Song> FetchByHash(string hash)
        {
            using (WebClient w = new WebClient())
            {
                w.Headers.Add("user-agent", $"{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Name}/{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version}");

                try
                {
                    string response = await w.DownloadStringTaskAsync($"{BeatSaverAPI}/by-hash/{hash.ToLower()}");
                    Song json = JsonConvert.DeserializeObject<Song>(response);
                    if (json != null)
                    {
                        return json;
                    }
                    else
                    {
                        Logger.Instance.Log($"Song with hash {hash} not found!");
                        return null;
                    }
                }
                catch (WebException wex)
                {
                    if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                    {
                        Logger.Instance.Log($"Song with hash {hash} not found!");
                    }
                    else
                    {
                        Logger.Instance.Exception($"Unable to fetch song by hash! Status code: {(int)((HttpWebResponse)wex.Response).StatusCode}({((HttpWebResponse)wex.Response).StatusCode})");
                    }
                    return null;
                }
                catch (Exception e)
                {
#if DEBUG
                    Logger.Instance.Exception(e);
#endif
                    return null;
                }
            }
        }

19 View Source File : RadioController.cs
License : MIT License
Project Creator : andruzzzhka

public static async void AddPlaylistToQueue(string path, int channelId)
        {
            bool remotePlaylist = path.ToLower().Contains("http://") || path.ToLower().Contains("https://");
            Playlist playlist = null;
            if (remotePlaylist)
            {
                using (WebClient w = new WebClient())
                {
                    w.Headers.Add("user-agent", $"{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Name}/{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version}");

                    try
                    {
                        string response = await w.DownloadStringTaskAsync(path);
                        playlist = JsonConvert.DeserializeObject<Playlist>(response);
                    }
                    catch (Exception e)
                    {
                        Logger.Instance.Error("Unable to add playlist to queue! Exception: "+e);
                        return;
                    }
                }
            }
            else
            {
                try
                {
                    string fullPath = Path.GetFullPath(path);
                    if (File.Exists(fullPath))
                    {
                        string content = await File.ReadAllTextAsync(fullPath);
                        playlist = JsonConvert.DeserializeObject<Playlist>(content);
                    }
                    else
                    {
                        Logger.Instance.Error($"Unable to add playlist to queue! File \"{path}\" does not exist!");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Logger.Instance.Error("Unable to add playlist to queue! Exception: " + e);
                    return;
                }
            }

            try
            {
                foreach(PlaylistSong song in playlist.songs)
                {
                    if (song == null)
                        continue;

                    if (!string.IsNullOrEmpty(song.hash))
                    {
                        if (song.hash.Length >= 40)
                        {
                            radioChannels[channelId].radioQueue.Enqueue(new SongInfo() { levelId = song.hash.ToUpper().Substring((song.hash.Length - 40), 40), songName = song.songName, key = song.key });
                            continue;
                        }
                    }

                    if (!string.IsNullOrEmpty(song.levelId))
                    {
                        if (song.levelId.Length >= 40)
                        {
                            radioChannels[channelId].radioQueue.Enqueue(new SongInfo() { levelId = song.levelId.ToUpper().Substring((song.hash.Length - 40), 40), songName = song.songName, key = song.key });
                            continue;
                        }
                    }

                    if (!string.IsNullOrEmpty(song.key))
                    {
                        SongInfo info = await BeatSaver.InfoFromID(song.key);
                        if(info != null)
                            radioChannels[channelId].radioQueue.Enqueue(info);
                        continue;
                    }
                }
                Logger.Instance.Log("Successfully added all songs from playlist to the queue!");
                File.WriteAllText($"RadioQueue{channelId}.json", JsonConvert.SerializeObject(radioChannels[channelId].radioQueue, Formatting.Indented));
            }
            catch (Exception e)
            {
                Logger.Instance.Error("Unable to add playlist to queue! Exception: " + e);
                return;
            }
        }

19 View Source File : BeatSaver.cs
License : MIT License
Project Creator : andruzzzhka

public static async Task<Song> FetchByID (string id)
        {
            using (WebClient w = new WebClient())
            {
                w.Headers.Add("user-agent", $"{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Name}/{System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version}");
                try
                {
                    string response = await w.DownloadStringTaskAsync($"{BeatSaverAPI}/detail/{id}");
                    Song json = JsonConvert.DeserializeObject<Song>(response);
                    return json;
                    
                }
                catch(WebException e)
                {
                    Logger.Instance.Warning($"Unable to fetch song with key {id}! Error code: {(int)((HttpWebResponse)e.Response).StatusCode}");
                    return null;
                }
                catch (Exception e)
                {
#if DEBUG
                    Logger.Instance.Exception($"Unable to fetch song with key {id}! Exception: {e}");
#endif
                    return null;
                }
            }
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : AndyFilter

public static Utils.GitHubRelease CheckVersion(string username, string repoName)
        {
            try
            {
                const string GITHUB_API = "https://api.github.com/repos/{0}/{1}/releases/latest";
                WebClient webClient = new WebClient();
                // Added user agent
                webClient.Headers.Add("User-Agent", "Unity web player");
                Uri uri = new Uri(string.Format(GITHUB_API, username, repoName));
                string releases = webClient.DownloadString(uri);
                return JsonSerializer.Deserialize<Utils.GitHubRelease>(releases);
            }
            catch
            {
                return null;
            }
        }

19 View Source File : WebUtils.cs
License : MIT License
Project Creator : AntonyCorbett

public static WebClient CreateWebClient()
        {
            var wc = new WebClient { Encoding = Encoding.UTF8 };
            wc.Headers.Add("user-agent", UserAgent);
            return wc;
        }

19 View Source File : ProductManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private static void DownloadLatest(ApexSettings settings, string manifestPath)
        {
            var client = new WebClient
            {
                BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
            };

            string serviceUrl = null;

            try
            {
                client.Headers.Add("Accept", "application/xml");
                var latestUpdate = XmlSingleValue(client.DownloadString("api/Service/GetLatestUpdateTime"));

                if (settings.lastUpdateCheck >= DateTime.Parse(latestUpdate, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.replacedumeUniversal | DateTimeStyles.AdjustToUniversal))
                {
                    settings.UpdateCompleted(null);
                    return;
                }

                client.Headers.Add("Accept", "application/xml");
                var productManifest = client.DownloadString("api/Products/GetProducts");
                using (var w = new StreamWriter(manifestPath))
                {
                    w.Write(productManifest);
                }

                client.Headers.Add("Accept", "application/xml");
                serviceUrl = XmlSingleValue(client.DownloadString("api/Service/GetServiceUrl"));
            }
            catch
            {
                return;
            }

            settings.UpdateCompleted(serviceUrl);
        }

19 View Source File : ProductManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

internal static void ApplyPatches(ProductInfo p, ApexSettings settings)
        {
            var client = new WebClient
            {
                BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
            };

            client.Headers.Add("Accept", "application/xml");
            var request = string.Format("api/Products/GetAvailablePatches?productName={0}&version={1}", p.generalName, p.installedVersion);
            var patchList = client.DownloadString(request);

            var doc = XDoreplacedent.Parse(patchList);
            var ns = XNamespace.Get(doc.Root.Attribute("xmlns").Value);
            var patchFiles = from s in XDoreplacedent.Parse(patchList).Root.Elements(ns + "string")
                             select s.Value;

            foreach (var patchFile in patchFiles)
            {
                var patchPath = string.Concat(settings.dataFolder, "/", patchFile);
                var url = string.Concat("content/patches/", patchFile);
                client.DownloadFile(url, patchPath);

                replacedetDatabase.ImportPackage(patchPath, false);
            }
        }

19 View Source File : HttpSignaling.cs
License : Apache License 2.0
Project Creator : araobp

private bool HTTPPost(string path, object data)
        {
            string str = JsonUtility.ToJson(data);
            byte[] bytes = new System.Text.UTF8Encoding().GetBytes(str);

            Debug.Log("Signaling: Posting HTTP data: " + str);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{m_url}/{path}");
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Headers.Add("Session-Id", m_sessionId);
            request.KeepAlive = false;

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(bytes, 0, bytes.Length);
                dataStream.Close();
            }

            return (HTTPParseTextResponse(HTTPGetResponse(request)) != null);
        }

19 View Source File : HttpSignaling.cs
License : Apache License 2.0
Project Creator : araobp

private bool HTTPConnect()
        {
            HttpWebRequest request =
                (HttpWebRequest)WebRequest.Create($"{m_url}/signaling/connection");
            request.Method = "PUT";
            request.ContentType = "application/json";
            request.Headers.Add("Session-Id", m_sessionId);
            request.KeepAlive = false;

            HttpWebResponse response = HTTPGetResponse(request);
            CreateConnectionResData data = HTTPParseJsonResponse<CreateConnectionResData>(response);

            if (data == null) return false;

            m_lastTimeGetOfferRequest = DateTimeExtension.ParseHttpDate(response.Headers[HttpResponseHeader.Date])
                .ToJsMilliseconds();

            m_mainThreadContext.Post(d => OnCreateConnection?.Invoke(this, data.connectionId), null);
            return true;
        }

19 View Source File : HttpSignaling.cs
License : Apache License 2.0
Project Creator : araobp

private bool HTTPGetOffers()
        {
            HttpWebRequest request =
                (HttpWebRequest)WebRequest.Create($"{m_url}/signaling/offer?fromtime={m_lastTimeGetOfferRequest}");
            request.Method = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("Session-Id", m_sessionId);
            request.KeepAlive = false;

            HttpWebResponse response = HTTPGetResponse(request);
            OfferResDataList list = HTTPParseJsonResponse<OfferResDataList>(response);

            if (list == null) return false;

            m_lastTimeGetOfferRequest = DateTimeExtension.ParseHttpDate(response.Headers[HttpResponseHeader.Date])
                .ToJsMilliseconds();

            foreach (var offer in list.offers)
            {
                m_mainThreadContext.Post(d => OnOffer?.Invoke(this, offer), null);
            }

            return true;
        }

19 View Source File : HttpSignaling.cs
License : Apache License 2.0
Project Creator : araobp

private bool HTTPGetAnswers()
        {
            HttpWebRequest request =
                (HttpWebRequest)WebRequest.Create($"{m_url}/signaling/answer?fromtime={m_lastTimeGetAnswerRequest}");
            request.Method = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("Session-Id", m_sessionId);
            request.KeepAlive = false;

            HttpWebResponse response = HTTPGetResponse(request);
            AnswerResDataList list = HTTPParseJsonResponse<AnswerResDataList>(response);

            if (list == null) return false;

            m_lastTimeGetAnswerRequest = DateTimeExtension.ParseHttpDate(response.Headers[HttpResponseHeader.Date])
                .ToJsMilliseconds();

            foreach (var answer in list.answers)
            {
                m_mainThreadContext.Post(d => OnAnswer?.Invoke(this, answer), null);
            }

            return true;
        }

19 View Source File : HttpSignaling.cs
License : Apache License 2.0
Project Creator : araobp

private bool HTTPGetCandidates()
        {
            HttpWebRequest request =
                (HttpWebRequest)WebRequest.Create($"{m_url}/signaling/candidate?fromtime={m_lastTimeGetCandidateRequest}");
            request.Method = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("Session-Id", m_sessionId);
            request.KeepAlive = false;

            HttpWebResponse response = HTTPGetResponse(request);
            CandidateContainerResDataList containers = HTTPParseJsonResponse<CandidateContainerResDataList>(response);

            if (containers == null) return false;
            m_lastTimeGetCandidateRequest = DateTimeExtension.ParseHttpDate(response.Headers[HttpResponseHeader.Date])
                .ToJsMilliseconds();

            foreach (var candidateContainer in containers.candidates)
            {
                foreach (var candidate in candidateContainer.candidates)
                {
                    candidate.connectionId = candidateContainer.connectionId;
                    m_mainThreadContext.Post(d => OnIceCandidate?.Invoke(this, candidate), null);
                }
            }

            return true;
        }

19 View Source File : SaliensApi.cs
License : MIT License
Project Creator : Archomeda

private static T DoRequest<T>(Uri uri, string data = null)
        {
            var isPost = data != null;
            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("User-Agent", "AutoSaliens/1.0 (https://github.com/Archomeda/AutoAliens)");
                if (isPost)
                    webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
#if DEBUG
                Program.Logger.LogMessage($"{{verb}}{(isPost ? "[POST]" : "[GET]")} {uri}");
#endif
                var json = isPost ? webClient.UploadString(uri, data) : webClient.DownloadString(uri);
                var eResult = webClient.ResponseHeaders["x-eresult"].ToString();
#if DEBUG
                Program.Logger.LogMessage($"{{verb}}EResult: {eResult}");
#endif
                if (!string.IsNullOrWhiteSpace(eResult) && eResult != "1")
                {
                    var message = webClient.ResponseHeaders["x-error_message"]?.ToString();
#if DEBUG
                    Program.Logger.LogMessage($"{{verb}}Error message: {message}");
#endif
                    throw SaliensApiException.FromString(eResult, message);
                }
                return JsonConvert.DeserializeObject<T>(json);
            }
        }

19 View Source File : SaliensApi.cs
License : MIT License
Project Creator : Archomeda

private static async Task<T> DoRequestAsync<T>(Uri uri, string data = null)
        {
            var isPost = data != null;
            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("User-Agent", "AutoSaliens/1.1 (https://github.com/Archomeda/AutoAliens)");
                if (isPost)
                    webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
#if DEBUG
                Program.Logger.LogMessage($"{{verb}}{(isPost ? "[POST]" : "[GET]")} {uri}");
#endif
                var json = isPost ? await webClient.UploadStringTaskAsync(uri, data) : await webClient.DownloadStringTaskAsync(uri);
                var eResult = webClient.ResponseHeaders["x-eresult"].ToString();
#if DEBUG
                Program.Logger.LogMessage($"{{verb}}EResult: {eResult}");
#endif
                if (!string.IsNullOrWhiteSpace(eResult) && eResult != "1")
                {
                    var message = webClient.ResponseHeaders["x-error_message"]?.ToString();
#if DEBUG
                    Program.Logger.LogMessage($"{{verb}}Error message: {message}");
#endif
                    throw SaliensApiException.FromString(eResult, message);
                }
                return JsonConvert.DeserializeObject<T>(json);
            }
        }

19 View Source File : UpdateChecker.cs
License : MIT License
Project Creator : Archomeda

private static async Task<string> GetUpdateFor(string branch)
        {
            if (string.IsNullOrWhiteSpace(AppDate))
                return null;

            var appDate = DateTime.Parse(AppDate);
            var uri = new Uri(AppVeyorApiUrl + $"?recordsNumber=50&branch={branch}");
            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("User-Agent", "AutoSaliens/1.0 (https://github.com/Archomeda/AutoAliens)");
                webClient.Headers.Add(HttpRequestHeader.Accept, "application/json");
                try
                {
                    var json = await webClient.DownloadStringTaskAsync(uri);
                    var builds = JObject.Parse(json)["builds"].AsJEnumerable();
                    foreach (JObject build in builds)
                    {
                        var buildDate = build["committed"].Value<DateTime>();
                        if (buildDate <= appDate)
                            break;
                        if (build.ContainsKey("pullRequestId"))
                            continue;
                        if (build["status"].Value<string>() == "success")
                            return build["version"].Value<string>();
                    }
                } catch (Exception) { }
            }
            return null;
        }

19 View Source File : SplashScreen.axaml.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private void CheckForUpdates()
        {
            Thread thr = new Thread(async () =>
            {
                try
                {
                    if (GlobalSettings.Settings.UpdateCheckDate < DateTime.Today.Ticks && (GlobalSettings.Settings.UpdateCheckMode == GlobalSettings.UpdateCheckModes.ProgramOnly || GlobalSettings.Settings.UpdateCheckMode == GlobalSettings.UpdateCheckModes.ProgramAndInstalledModules || GlobalSettings.Settings.UpdateCheckMode == GlobalSettings.UpdateCheckModes.ProgramAndAllModules))
                    {
                        ReleaseHeader programUpdate = null;

                        string releaseJson;

                        using (WebClient client = new WebClient())
                        {
                            client.Headers.Add("User-Agent", "arklumpus/TreeViewer");

                            releaseJson = await client.DownloadStringTaskAsync("https://api.github.com/repos/" + GlobalSettings.ProgramRepository + "/releases");
                        }

                        ReleaseHeader[] releases = System.Text.Json.JsonSerializer.Deserialize<ReleaseHeader[]>(releaseJson);

                        Version currVers = new Version(Program.Version);

                        for (int i = 0; i < releases.Length; i++)
                        {
                            try
                            {
                                if (!releases[i].prerelease)
                                {
                                    Version version = new Version(releases[i].tag_name.Substring(1));

                                    if (version > currVers)
                                    {
                                        programUpdate = releases[i];
                                        break;
                                    }
                                }
                            }
                            catch { }
                        }

                        if (programUpdate != null)
                        {
                            ProgramStartHandle.WaitOne();

                            await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                            {
                                UpdateWindow win = new UpdateWindow(programUpdate.name, programUpdate.html_url);
                                await win.ShowDialog2(GlobalSettings.Settings.MainWindows[0]);
                            });
                        }
                        else if (GlobalSettings.Settings.UpdateCheckMode == GlobalSettings.UpdateCheckModes.ProgramAndInstalledModules || GlobalSettings.Settings.UpdateCheckMode == GlobalSettings.UpdateCheckModes.ProgramAndAllModules)
                        {
                            Uri moduleHeaderInfo = new Uri(new Uri(GlobalSettings.Settings.ModuleRepositoryBaseUri), "modules.json.gz");

                            List<ModuleHeader> moduleHeaders;

                            using (WebClient client = new WebClient())
                            {
                                string tempFile = Path.GetTempFileName();
                                await client.DownloadFileTaskAsync(moduleHeaderInfo, tempFile);

                                using (FileStream fs = new FileStream(tempFile, FileMode.Open))
                                {
                                    using (GZipStream decompressionStream = new GZipStream(fs, CompressionMode.Decompress))
                                    {
                                        moduleHeaders = await System.Text.Json.JsonSerializer.DeserializeAsync<List<ModuleHeader>>(decompressionStream, Modules.DefaultSerializationOptions);
                                    }
                                }

                                File.Delete(tempFile);
                            }

                            bool newModules = false;
                            bool updatedModules = false;

                            for (int i = 0; i < moduleHeaders.Count; i++)
                            {
                                ModuleHeader header = moduleHeaders[i];

                                bool newModule = !Modules.LoadedModulesMetadata.TryGetValue(header.Id, out ModuleMetadata loadedModuleMetadata);

                                if (newModule)
                                {
                                    newModules = true;
                                }
                                else if (loadedModuleMetadata.Version < header.Version)
                                {
                                    updatedModules = true;
                                }
                            }

                            if ((newModules && GlobalSettings.Settings.UpdateCheckMode == GlobalSettings.UpdateCheckModes.ProgramAndAllModules) || updatedModules)
                            {
                                string message = null;

                                if (updatedModules)
                                {
                                    message = "Updates are available for some of the installed modules!";
                                }

                                if (newModules && GlobalSettings.Settings.UpdateCheckMode == GlobalSettings.UpdateCheckModes.ProgramAndAllModules)
                                {
                                    if (!string.IsNullOrEmpty(message))
                                    {
                                        message += "\n";
                                    }
                                    message += "New modules have been released. Check them out!";
                                }

                                if (!string.IsNullOrEmpty(message))
                                {
                                    message += "\nDo you wish to open the Module Repository?";

                                    ProgramStartHandle.WaitOne();

                                    await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                                    {
                                        MessageBox box = new MessageBox("Check for updates", message, MessageBox.MessageBoxButtonTypes.YesNo, MessageBox.MessageBoxIconTypes.QuestionMark);
                                        await box.ShowDialog2(GlobalSettings.Settings.MainWindows[0]);
                                        if (box.Result == MessageBox.Results.Yes)
                                        {
                                            ModuleManagerWindow win2 = new ModuleManagerWindow();
                                            _ = win2.ShowDialog2(GlobalSettings.Settings.MainWindows[0]);

                                            try
                                            {
                                                ModuleRepositoryWindow win = new ModuleRepositoryWindow(updatedModules ? ModuleRepositoryWindow.Modes.Install : ModuleRepositoryWindow.Modes.Load, win2);
                                                await win.ShowDialog2(win2);
                                            }
                                            catch (Exception ex)
                                            {
                                                await new MessageBox("Attention!", "An error occurred while looking up the module repository! Please check the address of the module repository.\n" + ex.Message).ShowDialog2(win2);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                        GlobalSettings.Settings.UpdateCheckDate = DateTime.Today.Ticks;
                        GlobalSettings.SaveSettings();
                    }
                }
                catch { }
            });
            thr.Start();
        }

19 View Source File : AboutWindow.axaml.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
            this.FindControl<TextBlock>("VersionTextBlock").Text = "Version " + Program.Version;

            this.FindControl<TextBlock>("GitHubTextBlock").PointerPressed += (s, e) =>
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
                {
                    FileName = "https://treeviewer.org",
                    UseShellExecute = true
                });
            };

            this.FindControl<Button>("CloseButton").Click += (s, e) =>
            {
                this.Close();
            };

            this.FindControl<Button>("CheckUpdatesButton").Click += async (s, e) =>
            {
                string releaseJson;

                ProgressWindow win = new ProgressWindow() { ProgressText = "Checking for updates..." };
                _ = win.ShowDialog2(this);

                try
                {

                    using (WebClient client = new WebClient())
                    {
                        client.Headers.Add("User-Agent", "arklumpus/TreeViewer");

                        releaseJson = await client.DownloadStringTaskAsync("https://api.github.com/repos/" + GlobalSettings.ProgramRepository + "/releases");
                    }

                    ReleaseHeader[] releases = System.Text.Json.JsonSerializer.Deserialize<ReleaseHeader[]>(releaseJson);

                    win.Close();

                    Version currVers = new Version(Program.Version);

                    bool found = false;

                    for (int i = 0; i < releases.Length; i++)
                    {
                        try
                        {
                            if (!releases[i].prerelease)
                            {
                                Version version = new Version(releases[i].tag_name.Substring(1));

                                if (version > currVers)
                                {
                                    found = true;

                                    UpdateWindow box = new UpdateWindow(releases[i].name, releases[i].html_url);
                                    await box.ShowDialog2(this);
                                    break;
                                }
                            }
                        }
                        catch { }
                    }

                    if (!found)
                    {
                        MessageBox box = new MessageBox("Check for updates", "The program is up to date!", MessageBox.MessageBoxButtonTypes.OK, MessageBox.MessageBoxIconTypes.Tick);
                        await box.ShowDialog2(this);
                    }
                }
                catch (Exception ex)
                {
                    win.Close();

                    MessageBox box = new MessageBox("Attention", "An error occurred while checking for updates!\n" + ex.Message);
                    await box.ShowDialog2(this);
                }
            };
        }

19 View Source File : IyzipayResourceV2.cs
License : MIT License
Project Creator : armutcom

private static WebHeaderCollection GetCommonHttpHeaders(BaseRequestV2 request)
        {
            WebHeaderCollection headers = new WebHeaderCollection();

#if NETSTANDARD
            headers["Accept"] = "application/json";
            headers[Constants.CLIENT_VERSION_HEADER] = Constants.CLIENT_VERSION;
            headers[CONVERSATION_ID_HEADER_NAME] = request.ConversationId;
#else
            headers.Add("Accept", "application/json");
            headers.Add(Constants.CLIENT_VERSION_HEADER, Constants.CLIENT_VERSION);
            headers.Add(CONVERSATION_ID_HEADER_NAME, request.ConversationId);
#endif
            return headers;
        }

19 View Source File : IyzipayResource.cs
License : MIT License
Project Creator : armutcom

protected static WebHeaderCollection GetHttpHeaders(BaseRequest request, Options options)
        {
            string randomString = DateTime.Now.ToString("ddMMyyyyhhmmssffff");
            WebHeaderCollection headers = new WebHeaderCollection();

#if NETSTANDARD
            headers["Accept"] = "application/json";
            headers[RANDOM_HEADER_NAME] = randomString;
            headers[CLIENT_VERSION] = "iyzipay-dotnet-2.1.15";
            headers[AUTHORIZATION] = PrepareAuthorizationString(request, randomString, options);
#else
            headers.Add("Accept", "application/json");
            headers.Add(RANDOM_HEADER_NAME, randomString);
            headers.Add(CLIENT_VERSION, "iyzipay-dotnet-2.1.15");
            headers.Add(AUTHORIZATION, PrepareAuthorizationString(request, randomString, options));
#endif
            return headers;
        }

19 View Source File : EventSource.cs
License : MIT License
Project Creator : AshV

protected virtual void ConfigureWebRequest(HttpWebRequest request)
        {
            request.Accept = "text/event-stream";
            request.AllowAutoRedirect = true;
            request.KeepAlive = true;
            request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            if (Headers != null) request.Headers.Add(Headers);
            if (!string.IsNullOrEmpty(LastEventId)) request.Headers.Add("Last-Event-Id", LastEventId);
        }

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 : 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"]);
            }
        }

See More Examples