public void SelectResponseCharacterEncoding_SelectsEncoding(string[] acceptCharsetHeaders, string requestEncoding, string[] supportedEncodings, string expectedEncoding) { // Arrange MockContentNegotiator negotiator = new MockContentNegotiator(); HttpRequestMessage request = new HttpRequestMessage(); foreach (string acceptCharsetHeader in acceptCharsetHeaders) { request.Headers.AcceptCharset.Add(StringWithQualityHeaderValue.Parse(acceptCharsetHeader)); } if (requestEncoding != null) { Encoding reqEncoding = Encoding.GetEncoding(requestEncoding); StringContent content = new StringContent("", reqEncoding, "text/plain"); request.Content = content; } MockMediaTypeFormatter formatter = new MockMediaTypeFormatter() { CallBase = true }; foreach (string supportedEncoding in supportedEncodings) { formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding)); } // Act Encoding actualEncoding = negotiator.SelectResponseCharacterEncoding(request, formatter); // Assert if (expectedEncoding == null) { Assert.Null(actualEncoding); } else { Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding); } }
public void Parse_Invalid() { try { StringWithQualityHeaderValue.Parse(null); Assert.Fail("#1"); } catch (FormatException) { } try { StringWithQualityHeaderValue.Parse(" "); Assert.Fail("#2"); } catch (FormatException) { } try { StringWithQualityHeaderValue.Parse("a,b"); Assert.Fail("#3"); } catch (FormatException) { } }
public static async Task <GetSharedSecretResponse> GetProvisioningResponse(HttpClient httpClient, string request) { var content = new StringContent(request, Encoding.UTF8, "application/xml"); var req = new HttpRequestMessage(HttpMethod.Post, PROVISIONING_URL); req.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("*/*")); req.Headers.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip")); req.Headers.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("deflate")); req.Content = content; var result = await httpClient.SendAsync(req); var resultTxt = await result.Content.ReadAsStringAsync(); var retval = XmlHelper.Deserialize <GetSharedSecretResponse>(resultTxt); return(retval); }
private async Task <List <Enemy> > RequestEnemiesAsync() { var client = new HttpClient(); var queryString = HttpUtility.ParseQueryString(string.Empty); // Request headers client.DefaultRequestHeaders.AcceptLanguage.Add(StringWithQualityHeaderValue.Parse("en")); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "fb4676955bae402fb50b49909808f425"); var uri = "https://www.haloapi.com/metadata/h5/metadata/enemies?" + queryString; var response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); var jsonResult = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject <Enemy[]>(jsonResult); return(result.ToList()); }
private static HttpRequestMessage PrepareSimpleGetRequest() { // Most relevant GET request headers considered simple: // * Accept // * Accept-Language // See also https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS var request = new HttpRequestMessage(HttpMethod.Get, "/"); var acceptedMediaType = MediaTypeWithQualityHeaderValue.Parse("text/plain"); request.Headers.Accept.Add(acceptedMediaType); var acceptedLanguage = StringWithQualityHeaderValue.Parse("en-us"); request.Headers.AcceptLanguage.Add(acceptedLanguage); return(request); }
public SearchClient(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger(nameof(SearchClient)) ?? throw new ArgumentNullException(nameof(loggerFactory)); var handlerWithDecompression = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }; this.client = new HttpClient(handlerWithDecompression) { BaseAddress = new Uri("http://www.google.com"), DefaultRequestHeaders = { Accept = { MediaTypeWithQualityHeaderValue.Parse("text/html"), MediaTypeWithQualityHeaderValue.Parse("application/xhtml+xml"), MediaTypeWithQualityHeaderValue.Parse("application/xml") }, AcceptEncoding = { StringWithQualityHeaderValue.Parse("gzip"), StringWithQualityHeaderValue.Parse("deflate") }, UserAgent = { ProductInfoHeaderValue.Parse("Chrome/10.0.648.151") } } }; }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (_localizationProvider.LanguageCode != null) { request.Headers.AcceptLanguage.Add(StringWithQualityHeaderValue.Parse(_localizationProvider.LanguageCode)); } if (_localizationProvider.CountryCode != null) { request.Headers.Add("VGG-Country", _localizationProvider.CountryCode); } if (_localizationProvider.CurrencyCode != null) { request.Headers.Add("Accept-Currency", _localizationProvider.CurrencyCode); } return(base.SendAsync(request, cancellationToken)); }
private static async Task <string> GetJson(string url) { using (var client = new HttpClient()) { using (var message = new HttpRequestMessage(HttpMethod.Get, url)) { message.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(CONTENTTYPE_JSON)); message.Headers.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("UTF-8")); var result = await client.SendAsync(message); if (result.IsSuccessStatusCode) { return(await result.Content.ReadAsStringAsync()); } } } return(null); }
private void CreateHttpClientOnce() { var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Automatic, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, }; _client = new HttpClient(handler); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip")); _client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("deflate")); var credentialsBytes = Encoding.UTF8.GetBytes($"{Config.TppUser}:{Config.TppPassword}"); var credentialsString = Convert.ToBase64String(credentialsBytes); _client.DefaultRequestHeaders.Add("Authorization", $"Basic {credentialsString}"); }
public void ComparerSortsListCorrectly(string[] unsorted, string[] expectedSorted) { // Arrange IEnumerable <StringWithQualityHeaderValue> unsortedValues = unsorted.Select( u => StringWithQualityHeaderValue.Parse(u) ); IEnumerable <StringWithQualityHeaderValue> expectedSortedValues = expectedSorted.Select( u => StringWithQualityHeaderValue.Parse(u) ); // Act IEnumerable <StringWithQualityHeaderValue> actualSorted = unsortedValues.OrderByDescending( m => m, StringWithQualityHeaderValueComparer.QualityComparer ); // Assert Assert.True(expectedSortedValues.SequenceEqual(actualSorted)); }
protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context) { // Use the value we stored in the Culture property of the caller's state when they connected if (context.Hub.Context.Request.Headers["Accept-Language"] != null) { var lang = context.Hub.Context.Request.Headers["Accept-Language"].Split(new[] { ',' }) .Select(a => StringWithQualityHeaderValue.Parse(a)) .Select(a => new StringWithQualityHeaderValue(a.Value, a.Quality.GetValueOrDefault(1))) .OrderByDescending(a => a.Quality) .Select(x => CultureInfo.GetCultureInfo(x.Value)) .FirstOrDefault(); if (lang != null) { Thread.CurrentThread.CurrentUICulture = lang; Thread.CurrentThread.CurrentCulture = lang; } } return(base.OnBeforeIncoming(context)); }
private static void ConfigureHttpClient(Uri baseAddress, HttpMessageHandler handler) { Client.BaseAddress = baseAddress; Client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip")); Client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("defalte")); Client.DefaultRequestHeaders.UserAgent.Add(GetUserAgent()); Client.DefaultRequestHeaders.Accept.Clear(); foreach (var mediaTypeHeader in Formatters.SelectMany(x => x.SupportedMediaTypes)) { Client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(mediaTypeHeader.MediaType)); } var clientHandler = handler as HttpClientHandler; if (clientHandler == null) { return; } clientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; }
/// <summary> /// 创建HttpClient /// </summary> /// <param name="apiAuthentication"></param> /// <returns>HttpClient</returns> private static HttpClient PrepareHttpClient(ApiAuthenticationEnum apiAuthentication, string data = "") { var handler = new HttpClientHandler { AllowAutoRedirect = false, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; // ssl请求 //handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;正式环境报错:他处理程序不支持自定义与此结合证书处理 var httpClient = new HttpClient(handler); var authentication = GetAuthenticationHeaderValue(apiAuthentication); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string salt = getsalt(), passid = getpassid(salt, data), timestamp = gettime(), signature = getsign(timestamp, salt, passid, data); httpClient.DefaultRequestHeaders.Add("passid", passid); httpClient.DefaultRequestHeaders.Add("timestamp", timestamp); httpClient.DefaultRequestHeaders.Add("salt", salt); httpClient.DefaultRequestHeaders.Add("signature", signature); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip")); httpClient.DefaultRequestHeaders.Authorization = authentication; return(httpClient); }
private ICompressor GetCompressor(IOwinRequest request) { if (!request.Headers.ContainsKey(AcceptEncoding)) { return(null); } return((from c in compressors from e in request.Headers.GetCommaSeparatedValues(AcceptEncoding).Select(x => StringWithQualityHeaderValue.Parse(x)) orderby e.Quality descending where string.Compare(c.ContentEncoding, e.Value, StringComparison.InvariantCultureIgnoreCase) == 0 select c).FirstOrDefault()); }
private void CheckInvalidParse(string input) { Assert.Throws <FormatException>(() => { StringWithQualityHeaderValue.Parse(input); }); }
private void CheckValidParse(string input, StringWithQualityHeaderValue expectedResult) { StringWithQualityHeaderValue result = StringWithQualityHeaderValue.Parse(input); Assert.Equal(expectedResult, result); }
public async Task <List <LanguageDTO> > GetLanguageListFromLocale(List <LanguageDTO> languageListServer) { var locale = _utilityService.GetLocale(_accessor.HttpContext.Request.Headers); if (!string.IsNullOrWhiteSpace(locale) && (locale.Equals(Constants.DEFAULT_REQUEST_HEADER_ACCEPT_LANGUAGE, StringComparison.OrdinalIgnoreCase))) { locale = Constants.REQUEST_HEADER_ACEPT_LANGUAGE; } var languages = Enumerable.Empty <StringWithQualityHeaderValue>().OrderBy(s => s); if (!string.IsNullOrWhiteSpace(locale)) { languages = locale.Split(new[] { ',' }) .Select(a => StringWithQualityHeaderValue.Parse(a)) .Select(a => new StringWithQualityHeaderValue(a.Value, a.Quality.GetValueOrDefault(1))) .OrderByDescending(a => a.Quality); } var languageDict = new Dictionary <int, LanguageDTO>(); LanguageDTO language = null; if (languageListServer == null) { languageListServer = await _cacheService.GetAllAsync("languagesCacheKey"); } //This will return there primary language first as per the locale //Need special handling for simplied and traditional chinese. Both start with zh so we need additional code //to handle the case bool isChineseTraditional = false; bool isChineseSimplified = false; int preferredLanguageId = 0; string preferredLanguage = ""; foreach (var lang in languages) { language = await SelectLanguageAsync(lang.Value, languageListServer); if (language != null) { preferredLanguageId = language.LanguageId; preferredLanguage = language.Locale.Split('-')[0]; languageDict.Add(language.LanguageId, language); if (language.Locale.ToLower() == "zh-tw" || language.Locale.ToLower() == "zh-hk") { isChineseTraditional = true; } else if (language.Locale.ToLower() == "zh-cn" || language.Locale.ToLower() == "zh-sg") { isChineseSimplified = true; } } } //See if we can grab any other languages that would be useful to display the article in if the //primary language is not available //It just needs to look over all languages in the database and see if we find any thing that we consider //a match - ie the first 2 digits of the local match //var languageListServer = await _cacheService.GetAllAsync("languagesCacheKey"); //Need special handling for chinese simplifed and traditional if (isChineseTraditional) { //Add remaining chinese traditional languages foreach (var item in languageListServer) { if (preferredLanguageId != item.LanguageId && item.Locale.ContainsAny(Constants.ChineseTraditional, StringComparison.OrdinalIgnoreCase)) { languageDict.Add(item.LanguageId, item); } } } else if (isChineseSimplified) { //Add remaining chinese simplifed languages foreach (var item in languageListServer) { if (preferredLanguageId != item.LanguageId && item.Locale.ContainsAny(Constants.ChineseSimplified, StringComparison.OrdinalIgnoreCase)) { languageDict.Add(item.LanguageId, item); } } } //Add any remaining languages to the list. This will match on the first part of the locale string ie es or zh foreach (var item in languageListServer) { if (item.Locale.Split('-')[0] == preferredLanguage && !languageDict.ContainsKey(item.LanguageId)) { languageDict.Add(item.LanguageId, item); } } //Didn't get a language so just grab the default one if (languageDict.Count == 0) { var defaultLocalizationIdentifier = _appSettings.Value.DefaultLanguageId; var defaultLanguage = await SelectLanguageAsync(defaultLocalizationIdentifier, languageListServer); languageDict.Add(defaultLanguage.LanguageId, defaultLanguage); } var languageList = languageDict.Values.ToList(); return(languageList); }
public void Parse_SetOfInvalidValueStrings_Throws(string input) { Assert.Throws <FormatException>(() => StringWithQualityHeaderValue.Parse(input)); }