예제 #1
0
        public async Task <T> PerformAsync <T>(Method paramMethod, Object paramObject) where T : new()
        {
            RestClient localClient = RestClientHelper.GetDefaultRestClient(new Uri(TerodoViewApiBase.UrlEndpoint));

            localClient.AddDefaultHeaders();
            if (String.IsNullOrEmpty(TerodoViewApiBase.Token?.token))
            {
                await(new TerodoViewApiToken()).GetTokenAsync();
            }

            RestRequest localRequest = RestClientHelper.GetDefaultRestRequest(Resource, paramMethod, paramObject);

            localRequest.AddAuthencationHeaders();

            try
            {
                IRestResponse localResponse = await RestClientBase.ExecuteCallAsync(localClient, localRequest);

                return(JsonConvert.DeserializeObject <T>(localResponse.Content, RestClientHelper.DefaultJsonSerializerSettings));
            }
            finally
            {
                localClient  = null;
                localRequest = null;
            }
        }
예제 #2
0
        public async Task <T> Execute <T>(IRestRequest request, string auth = null) where T : class
        {
            var client = new RestClient(_config.BaseUrl);

            if (string.IsNullOrEmpty(auth))
            {
                auth = await ValidAuth();
            }

            client.AddDefaultHeaders(new Dictionary <string, string>
            {
                { "Authorization", auth },
                { "Ubi-AppId", _config.AppId },
                { "Content-Type", "application/json" }
            });

            var response = Policy
                           .HandleResult <IRestResponse <T> >(m => m.StatusCode != HttpStatusCode.OK)
                           .WaitAndRetry(
                3,
                i => TimeSpan.FromSeconds(2),
                (result, timeSpan, retryCount, context) =>
            {
                _log.LogError($"Request failed to /{result.Result.Request.Resource}. Error: {result.Result.StatusCode}");
            })
                           .Execute(() => client.Execute <T>(request));

            return(response.Data);
        }
예제 #3
0
        public static async Task <IRestResponse> GetAsync(string uid)
        {
            //https://api-takumi.mihoyo.com/game_record/genshin/api/index?server=cn_gf01&role_id=112075042

            var client = new RestClient(
                $"https://api-takumi.mihoyo.com/game_record/genshin/api/index?server=cn_gf01&role_id={uid}");

            client.AddDefaultHeaders(new Dictionary <string, string>
            {
                {
                    "Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
                },
                { "Origin", "https://webstatic.mihoyo.com" },
                { "Accept-Encoding", "gzip, deflate" },
                { "Accept-Language", "zh-CN,zh;q=0.9,zh-HK;q=0.8" },
                {
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"
                },
                { "DS", GetDS() },
                { "Rferer", "https://webstatic.mihoyo.com/app/community-game-records/index.html?v=6" },
                { "x-rpc-app_version", "2.1.0" },
                { "x-rpc-client_type", "4" },
                { "X-Requested-With", "com.mihoyo.hyperion" }
            });

            return(await client.ExecuteAsync(new RestRequest(Method.GET)));
        }
예제 #4
0
        public Pterodactyl(string hostname, string key)
        {
            if (key == null)
            {
                throw new Exception("No keys are provided. Provide at least a Client Key or Application Key");
            }

            if (hostname.Length <= 5)
            {
                throw new PterodactylException("Invalid host name set, Please set one.");
            }

            var regex = new Regex("http(s?)://");
            var host  = regex.Match(hostname).Success ? hostname : $"https://{hostname}/";

            HttpClient = new RestClient(host);
            HttpClient.UseSerializer <NewtonsoftSerializer>();
            HttpClient.AddDefaultHeaders(new Dictionary <string, string>()
            {
                { "Authorization", $"Bearer {key}" },
                { "Accept", "Application/vnd.pterodactyl.v1+json" }
            });

            V0_7     = new PterodactylV0_7(HttpClient);
            V1_0     = new PterodactylV1_0(HttpClient);
            Instance = this;
        }
예제 #5
0
        private RestClient BuildRequest(string url)
        {
            var rc = new RestClient {
                BaseUrl = new Uri(url)
            };

            rc.AddDefaultHeaders(new Dictionary <string, string>
            {
                { "User-Agent", _userAgent },
                { "DS", GetDs() },
                { "x-rpc-client_type", "5" },
                { "x-rpc-app_version", _config.AppVersion },
                { "Origin", "https://webstatic.mihoyo.com" },
                { "Accept", "application/json, text/plain, */*" },
                { "X-Requesed-With", "com.mihoyo.hyperion" },
                { "Sec-Fetch-Site", "same-site" },
                { "Sec-Fetch-Mode", "cors" },
                { "Sec-Fetch-Dest", "empty" },
                { "Referer", "https://webstatic.mihoyo.com/" },
                { "Accept-Encoding", "gzip, deflate" },
                { "Accept-Language", "en-GB,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-US;q=0.6" },
                { "Cookie", Uid.IsChineseServer() ? _config.Cookie : _config.OsCookie }
            });

            return(rc);
        }
예제 #6
0
 public PocketController(ILogger <PocketController> logger, IConfiguration configuration)
 {
     _logger        = logger;
     _configuration = configuration;
     _consumerKey   = _configuration.GetValue <string>("PocketConsumerKey");
     _client.AddDefaultHeaders(DefaultApiHeaders());
 }
 /// <summary>
 /// If authentication is enabled, add the authentication header
 /// Add any other headers
 /// </summary>
 /// <param name="client">Pass in an instance of RestClient and add headers to it.</param>
 /// <param name="headers"></param>
 /// <param name="authMode">Specify the authentication mode if different than the default</param>
 void AddDefaultHeader(ref RestClient client, Dictionary <string, string> headers, AuthMode authMode = AuthMode.Token)
 {
     try
     {
         Dictionary <string, string> defaultHeaders = new Dictionary <string, string>();
         if (_curAuthMode == AuthMode.Token && authMode == AuthMode.Token)
         {
             defaultHeaders.Add("Authorization", "Bearer " + _apiToken);
         }
         if (headers != null && headers.Count > 0)
         {
             foreach (var item in headers)
             {
                 defaultHeaders.Add(item.Key, item.Value);
             }
         }
         if (defaultHeaders.Count > 0)
         {
             client.AddDefaultHeaders(defaultHeaders);
         }
     }
     catch (Exception e)
     {
         throw GetException("AddDefaultHeader", e);
     }
 }
예제 #8
0
        public ApiDriver(ApiDriverOptions?options = null)
        {
            var apiAttr = typeof(TApi).GetCustomAttribute <ApiAttribute>();

            var url = apiAttr.Url;

            if (url == null)
            {
                if (apiAttr.UrlProvider == null)
                {
                    throw new Exception($"Provider [{nameof(ApiAttribute.Url)}] or [{nameof(ApiAttribute.UrlProvider)}] propertires for [{typeof(ApiAttribute).FullName}] attribute.");
                }

                if (!typeof(IUrlProvider).IsAssignableFrom(apiAttr.UrlProvider))
                {
                    throw new Exception($"[{nameof(ApiAttribute.UrlProvider)}] type in [{typeof(ApiAttribute).FullName}] attribute must implements [{typeof(IUrlProvider).FullName}] interface.");
                }

                url = ((IUrlProvider)Activator.CreateInstance(apiAttr.UrlProvider)).GetUrl(typeof(TApi));
            }

            if (url == null)
            {
                throw new Exception($"Neither [{nameof(ApiAttribute.Url)}] nor [{nameof(ApiAttribute.UrlProvider)}] provided not null string.");
            }

            client = new RestClient(url);

            var headerAttrs = typeof(TApi).GetCustomAttributes <ApiHeaderAttribute>();

            if (headerAttrs.Any())
            {
                var headersFromAttrs = headerAttrs.ToDictionary(attr => attr.Name.ToLower(), attr => attr.Value);
                client.AddDefaultHeaders(headersFromAttrs);
                headers = headers.Union(headersFromAttrs).ToDictionary(kv => kv.Key, kv => kv.Value);
            }

            if (options?.Headers != null)
            {
                var headersFromOpts = options?.Headers.ToDictionary(kv => kv.Key.ToLower(), kv => kv.Value);
                client.AddDefaultHeaders(headersFromOpts);
                headers = headers.Union(headersFromOpts).ToDictionary(kv => kv.Key, kv => kv.Value);
            }

            Api = DispatchProxy.Create <TApi, ApiProxy>();
            ((ApiProxy)(Api as object)).Init(this);
        }
예제 #9
0
 public HistoricalDataService()
 {
     Client = new RestClient("https://yahoo-finance15.p.rapidapi.com/api/yahoo");
     Client.AddDefaultHeaders(new Dictionary <string, string>()
     {
         { "x-rapidapi-host", "yahoo-finance15.p.rapidapi.com" },
         { "x-rapidapi-key", "aeabafe2c8msh97867dc0d3cc332p128d50jsn94882f7d936a" },
         { "useQueryString", "true" }
     });
 }
예제 #10
0
        private void initializeClients()
        {
            //RestClient
            restClient.AddDefaultHeaders(headers);

            //httpClient
            foreach (var item in headers)
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(item.Value));
            }
        }
예제 #11
0
        private void SetupDefaultHeader(int wordCount, int minWordLength, int maxWordLength)
        {
            headers.Add("Authorization", "MatthewIsTheGreatest1234");
            headers.Add("Token", "Test"); // token not used in this version
            _client.AddDefaultHeaders(headers);
            WordRequestModel word = new WordRequestModel()
            {
                WordCount = wordCount, MaxWordLength = maxWordLength, MinWordLength = minWordLength
            };

            restRequest.AddJsonBody(word);
        }
예제 #12
0
        public WeatherAPI()
        {
            // Создаём словарь заголовоков
            Dictionary <string, string> headers = new Dictionary <string, string>
            {
                // Добвляем значения в словарь
                { "x-rapidapi-host", "community-open-weather-map.p.rapidapi.com" },
                { "x-rapidapi-key", "4b3ce770c3msh089eaf260cd3ff2p1c7618jsnf7c6643d955c" }
            };

            // инициализация клиента
            restClient.BaseUrl = new Uri("https://community-open-weather-map.p.rapidapi.com/");
            restClient.AddDefaultHeaders(headers);
        }
예제 #13
0
        public void AddDefaultHeadersUsingDictionary()
        {
            var headers = new Dictionary <string, string>
            {
                { "Content-Type", "application/json" },
                { "Accept", "application/json" },
                { "Content-Encoding", "gzip, deflate" }
            };

            var expected = headers.Select(x => new Parameter(x.Key, x.Value, ParameterType.HttpHeader));

            var client = new RestClient(BaseUrl);

            client.AddDefaultHeaders(headers);

            expected.Should().BeSubsetOf(client.DefaultParameters);
        }
예제 #14
0
        public NutritionixService(IOptions <NutritionixApiOptions> options)
        {
            _client = new RestClient(Url);
            var headers = new Dictionary <string, string>()
            {
                { "Content-Type", "application/x-www-form-urlencoded" },
                { "x-app-id", options.Value.XAppId },
                { "x-app-key", options.Value.XAppKey }
            };

            _client.AddDefaultHeaders(headers);

            _serializationOptions = new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            };
        }
        public WinningRestaurant GetWinningRestaurant(string winningId)
        {
            var client = new RestClient("https://api.yelp.com/v3/businesses");

            client.AddDefaultHeaders(new Dictionary <string, string> {
                { "Authorization", $"Bearer {_key}" }
            });

            var request  = new RestRequest($"/{winningId}");
            var response = client.Get <WinningRestaurant>(request);

            if (!response.IsSuccessful)
            {
                return(null);
            }
            return(response.Data);
        }
        public AllRestaurantData GetNext20Resturants(string City, string categories, int offSet)
        {
            var client = new RestClient("https://api.yelp.com/v3/businesses/search");

            client.AddDefaultHeaders(new Dictionary <string, string> {
                { "Authorization", $"Bearer {_key}" }
            });

            var request  = new RestRequest($"?location={City}&categories={categories}&offset={offSet}");
            var response = client.Get <AllRestaurantData>(request);

            if (!response.IsSuccessful)
            {
                return(null);
            }
            return(response.Data);
        }
예제 #17
0
    public void AddDefaultHeadersUsingDictionary()
    {
        var headers = new Dictionary <string, string> {
            { KnownHeaders.ContentType, "application/json" },
            { KnownHeaders.Accept, "application/json" },
            { KnownHeaders.ContentEncoding, "gzip, deflate" }
        };

        var expected = headers.Select(x => new HeaderParameter(x.Key, x.Value));

        var client = new RestClient(BaseUrl);

        client.AddDefaultHeaders(headers);

        var actual = client.DefaultParameters.Select(x => x as HeaderParameter);

        expected.Should().BeSubsetOf(actual);
    }
예제 #18
0
        public HttpStatusCode CHECK_BLOCK(string u, string Cookies)
        {
            client       = new RestClient(API_BASE);
            client.Proxy = null;
            request      = new RestRequest(SET_PATH, Method.POST);
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("X-CSRFToken", "missing");
            headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            headers.Add("Connection", "close");
            request.AddCookie("sessionid", Cookies);
            client.UserAgent = USER_AGENT;
            client.AddDefaultHeaders(headers);
            request.AddParameter("", $"username={u}", ParameterType.RequestBody);
            var execute = client.Execute(request);

            return(execute.StatusCode);
        }
예제 #19
0
        public HttpStatusCode Consent(string Cookies)
        {
            client       = new RestClient(API_BASE);
            client.Proxy = null;
            request      = new RestRequest(CONSENT_PATH, Method.POST);
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("X-CSRFToken", "missing");
            headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            headers.Add("Connection", "keep-alive");
            request.AddCookie("sessionid", Cookies);
            client.UserAgent = USER_AGENT;
            client.AddDefaultHeaders(headers);
            request.AddParameter("signed_body", "SIGNATURE.{\"current_screen_key\":\"dob\",\"day\":\"1\",\"year\":\"1998\",\"month\":\"1\"}", ParameterType.RequestBody);
            var execute = client.Execute(request);

            return(execute.StatusCode);
        }
        public AllRestaurantData GetNext20ResturantsByCoordinates(string coordinates, string cityParams, int offset)
        {
            var client = new RestClient("https://api.yelp.com/v3/businesses/search");

            client.AddDefaultHeaders(new Dictionary <string, string> {
                { "Authorization", $"Bearer {_key}" }
            });

            var coordinatesSplit = coordinates.Split(",");
            var latitude         = coordinatesSplit[0];
            var longitude        = coordinatesSplit[1];
            var request          = new RestRequest($"?latitude={latitude}&longitude={longitude}&categories={cityParams}&offset={offset}");
            var response         = client.Get <AllRestaurantData>(request);

            if (!response.IsSuccessful)
            {
                return(null);
            }
            return(response.Data);
        }
예제 #21
0
        public string CURRENT_USER(string Cookies)
        {
            client       = new RestClient(API_BASE);
            client.Proxy = null;
            request      = new RestRequest(CURRENT_PATH, Method.GET);
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("X-CSRFToken", "missing");
            headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            headers.Add("Connection", "close");
            request.AddCookie("sessionid", Cookies);
            client.UserAgent = USER_AGENT;
            client.AddDefaultHeaders(headers);
            var execute = client.Execute(request);

            username     = Regex.Match(execute.Content, "\"username\":\"(.*?)\"").Groups[1].Value;
            email        = Regex.Match(execute.Content, "\"email\":\"(.*?)\"").Groups[1].Value;
            phone_number = Regex.Match(execute.Content, "\"phone_number\":\"(.*?)\"").Groups[1].Value;
            biography    = Regex.Match(execute.Content, "\"biography\":\"(.*?)\"").Groups[1].Value;
            return(username);
        }
예제 #22
0
    public NStackRepository(NStackConfiguration configuration)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }

        if (string.IsNullOrWhiteSpace(configuration.ApiKey))
        {
            throw new ArgumentNullException(configuration.ApiKey);
        }

        if (string.IsNullOrWhiteSpace(configuration.ApplicationId))
        {
            throw new ArgumentNullException(configuration.ApplicationId);
        }

        if (string.IsNullOrWhiteSpace(configuration.BaseUrl))
        {
            throw new ArgumentNullException(configuration.BaseUrl);
        }

        var options = new RestClientOptions(configuration.BaseUrl);

        Client = new RestClient(options);
        Client.UseSystemTextJson(new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            Converters =
            {
                new JsonStringEnumConverter()
            }
        });

        Client.AddDefaultHeaders(new Dictionary <string, string>
        {
            { "X-Application-Id", configuration.ApplicationId },
            { "X-Rest-Api-Key", configuration.ApiKey }
        });
    }
예제 #23
0
        public bool CHECK_14(string target)
        {
            bool check = false;

            client       = new RestClient(WEB_BASE);
            client.Proxy = null;
            request      = new RestRequest(CHECK14_PATH, Method.POST);
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("X-CSRFToken", "missing");
            headers.Add("Content-Type", "application/x-www-form-urlencoded");
            client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0";
            client.AddDefaultHeaders(headers);
            request.AddParameter("hacker", $"email=&username={target}&first_name=&opt_into_one_tap=false", ParameterType.RequestBody);
            var execute = client.Execute(request);

            if (execute.Content.Contains("username_held_by_others"))
            {
                check = true;
            }

            return(check);
        }
예제 #24
0
 public void Setup()
 {
     _client = new RestClient(BaseUrl);
     _client.AddDefaultHeaders(_headers);
 }
예제 #25
0
        /// <summary>
        /// 政务钉请求
        /// </summary>
        /// <param name="method"></param>
        /// <param name="canonicalURI"></param>
        /// <param name="requestParas"></param>
        /// <returns></returns>
        public static string DingGovRequest(Method method, string canonicalURI,
                                            Dictionary <string, string> requestParas = null)
        {
            var timestamp  = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
            var nonce      = ConvertDateTimeToInt(DateTime.Now) + "1234";
            var requestUrl = AppSetting.GetSection("ZDingTalk:DingUrl").ToString();  //域名配置地址

            var client = new RestClient(requestUrl);

            try
            {
                var request = new RestRequest(canonicalURI, method);

                var bytesToSign = $"{method}\n{timestamp}\n{nonce}\n{canonicalURI}";
                if (requestParas?.Count() > 0)
                {
                    requestParas = requestParas.OrderBy(m => m.Key).ToDictionary(m => m.Key, p => p.Value);
                    //参数参与签名
                    bytesToSign += '\n' + DicionartyToUrlParameters(requestParas);
                }

                #region 请求头

                Dictionary <string, string> dict = new Dictionary <string, string>()
                {
                    // {"X-Hmac-Auth-IP","1.1.1.1"},
                    // {"X-Hmac-Auth-MAC","MAC"},
                    { "X-Hmac-Auth-Timestamp", timestamp },
                    { "X-Hmac-Auth-Version", "1.0" },
                    { "X-Hmac-Auth-Nonce", nonce },
                    { "apiKey", AppSetting.GetSection("ZDingTalk:AppKey").ToString() },
                    { "Content-Type", "application/json" },
                    { "X-Hmac-Auth-Signature", GetSignature(bytesToSign, AppSetting.GetSection("ZDingTalk:AppSecret").ToString()) },
                };
                client.AddDefaultHeaders(dict);
                #endregion

                if (method == Method.POST)
                {
                    var paras = new Dictionary <string, string>();
                    if (requestParas?.Count() > 0)
                    {
                        foreach (var dic in requestParas)
                        {
                            //paras.Add(dic.Key, Uri.UnescapeDataString(dic.Value));
                            request.AddParameter(dic.Key, Uri.UnescapeDataString(dic.Value));
                        }
                    }
                }
                else if (method == Method.GET)
                {
                    requestUrl += $"?{DicionartyToUrlParameters(requestParas)}";
                }
                var response = client.Execute(request);
                if (!response.IsSuccessful)
                {
                    throw new Exception(response.Content);
                }
                return(response.Content);
            }
            catch (Exception ex)
            {
                //记录日志
                throw;
            }
        }