public void GHIssue8342(HttpStatusCode expectedStatus, string validUsername, string validPassword, string username, string password) { // create a http client to use with some creds that we do know are not valid var handler = new NSUrlSessionHandler() { Credentials = new NetworkCredential(username, password, "") }; var client = new HttpClient(handler); bool done = false; HttpStatusCode httpStatus = HttpStatusCode.NotFound; Exception ex = null; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { try { var result = await client.GetAsync($"https://httpbin.org/basic-auth/{validUsername}/{validPassword}"); httpStatus = result.StatusCode; } catch (Exception e) { ex = e; } finally { done = true; } }, () => done); if (!done) // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail { Assert.Inconclusive("Request timedout."); } else { Assert.IsNull(ex, "Exception not null"); Assert.AreEqual(expectedStatus, httpStatus, "Status not ok"); } }
public override async void ViewDidLoad() { base.ViewDidLoad(); var user = UserManager.Instance; var accessToken = await user.GetAccessTokenAsync(); if (accessToken == null || accessToken.ValidTo < DateTime.UtcNow) { TempWeatherDisplay.Text = "Not logged in."; return; } // To support TLS 1.2: var nsUrlSessionHandler = new NSUrlSessionHandler(); IApiClient apiClient = new ApiClient(accessToken.RawData, nsUrlSessionHandler); var result = await apiClient.GetWeatherAsync(); TempWeatherDisplay.Text = $"Temperature: {result.Temperature}℃\n" + $"Humidity: {result.Humidity}%\n" + $"Wind Speed: {result.WindSpeedAverage}km/h (gusts to {result.WindSpeedGust}km/h)\n" + $"Wind Direction: {result.WindDirection}º\n" + $"Rainfall: {result.Rainfall}mm"; }
public void Should_CreatePipeline_Without_CompressionHandler() { using (AuthenticationHandler authenticationHandler = (AuthenticationHandler)GraphClientFactory.CreatePipeline(handlers)) using (RetryHandler retryHandler = (RetryHandler)authenticationHandler.InnerHandler) using (RedirectHandler redirectHandler = (RedirectHandler)retryHandler.InnerHandler) #if iOS using (NSUrlSessionHandler innerMost = (NSUrlSessionHandler)redirectHandler.InnerHandler) #elif macOS using (Foundation.NSUrlSessionHandler innerMost = (Foundation.NSUrlSessionHandler)redirectHandler.InnerHandler) #endif { Assert.NotNull(authenticationHandler); Assert.NotNull(retryHandler); Assert.NotNull(redirectHandler); Assert.NotNull(innerMost); Assert.IsType <AuthenticationHandler>(authenticationHandler); Assert.IsType <RetryHandler>(retryHandler); Assert.IsType <RedirectHandler>(redirectHandler); #if iOS Assert.IsType <NSUrlSessionHandler>(innerMost); #elif macOS Assert.IsType <Foundation.NSUrlSessionHandler>(innerMost); #endif } }
public void TestNSurlSessionHandlerCookieContainerSetCookie() { var url = NetworkResources.Httpbin.GetSetCookieUrl("cookie", "chocolate-chip"); var cookieContainer = new CookieContainer(); string nativeCookieResult = null; Exception ex = null; var completed = false; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { try { var nativeHandler = new NSUrlSessionHandler() { AllowAutoRedirect = true, CookieContainer = cookieContainer, }; var nativeClient = new HttpClient(nativeHandler); var nativeResponse = await nativeClient.GetAsync(url); nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync(); } catch (Exception e) { ex = e; } finally { completed = true; } }, () => completed); Assert.IsNull(ex, "Exception"); Assert.IsNotNull(nativeCookieResult, "Native cookies result"); var cookiesFromServer = cookieContainer.GetCookies(new Uri(url)); Assert.AreEqual(1, cookiesFromServer.Count, "Cookies received from server."); }
public HttpMessageHandler Create(bool enableDebugTracing = false) { var nativeClientHandler = new NSUrlSessionHandler(); return(enableDebugTracing ? new HttpTraceHandler(nativeClientHandler) : (HttpMessageHandler)nativeClientHandler); }
static HttpMessageHandler CreateHttpMessageHandler() { // https://docs.microsoft.com/zh-cn/xamarin/cross-platform/macios/http-stack var handler = new NSUrlSessionHandler(); AddFiddlerRootCertificate(handler); return(handler); }
public void NS302_Disallowed() { var handler = new NSUrlSessionHandler(); handler.AllowAutoRedirect = false; var client = new HttpClient(handler); Get302(client, allowRedirect: handler.AllowAutoRedirect); }
public void NSUrlSession() { using (var handler = new NSUrlSessionHandler()) { Assert.True(handler.AllowAutoRedirect, "AllowAutoRedirect"); Assert.Null(handler.Credentials, "Credentials"); // custom, not in HttpClientHandler Assert.False(handler.DisableCaching, "DisableCaching"); } }
protected BaseRestConsumer(NSUrlSessionHandler handler, IStorage storage) { this.storage = storage; client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(timeOutInSeconds) }; }
public void HttpProvider_CustomNSUrlSessionHandler() { using (var httpClientHandler = new NSUrlSessionHandler()) using (var httpProvider = new HttpProvider(httpClientHandler, false, null)) { Assert.Equal(httpClientHandler, httpProvider.httpMessageHandler); Assert.True(httpProvider.httpClient.DefaultRequestHeaders.Contains(CoreConstants.Headers.FeatureFlag)); Assert.False(httpProvider.disposeHandler); } }
public void TestNSUrlSessionEphemeralDisabledCookies() { // assert we do throw an exception with ephmeral configs. using (var config = NSUrlSessionConfiguration.EphemeralSessionConfiguration) { Assert.True(config.SessionType == NSUrlSessionConfiguration.SessionConfigurationType.Ephemeral, "Session type."); var nativeHandler = new NSUrlSessionHandler(config); Assert.Throws <InvalidOperationException> (() => { nativeHandler.UseCookies = false; }); } }
public void AssertDefaultValuesNSUrlSessionHandler() { using (var handler = new NSUrlSessionHandler()) { Assert.True(handler.AllowAutoRedirect, "Default redirects value"); Assert.True(handler.AllowsCellularAccess, "Default cellular data value."); } using (var config = NSUrlSessionConfiguration.DefaultSessionConfiguration) { config.AllowsCellularAccess = false; using (var handler = new NSUrlSessionHandler(config)) { Assert.False(handler.AllowsCellularAccess, "Configuration cellular data value."); } } }
public GraphService() { var authProvider = GetAuthProvider(); // Use AndroidClientHandler as opposed to HttpClientHandler. var innerHandler = new NSUrlSessionHandler { AllowAutoRedirect = false }; var handlers = GraphClientFactory.CreateDefaultHandlers(authProvider); //handlers.RemoveAt(1); var pipeline = GraphClientFactory.CreatePipeline(handlers, innerHandler); GraphClient = new GraphServiceClient(authProvider, new HttpProvider(pipeline, true, new Serializer())); }
public void TestNSUrlSessionDefaultDisableCookiesWithManagedContainer() { // simple test. send a request with a set-cookie url, get the data // and ensure that the second request does not send any cookies. var url = NetworkResources.Httpbin.GetSetCookieUrl("cookie", "chocolate-chip"); string nativeSetCookieResult = null; string nativeCookieResult = null; var cookieContainer = new CookieContainer(); Exception ex = null; var completed = false; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { try { var nativeHandler = new NSUrlSessionHandler() { AllowAutoRedirect = true, UseCookies = false, }; var nativeClient = new HttpClient(nativeHandler); var nativeResponse = await nativeClient.GetAsync(url); nativeSetCookieResult = await nativeResponse.Content.ReadAsStringAsync(); // got the response, preform a second queries to the cookies endpoint to get // the actual cookies sent from the storage nativeResponse = await nativeClient.GetAsync(NetworkResources.Httpbin.CookiesUrl); nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync(); } catch (Exception e) { ex = e; } finally { completed = true; } }, () => completed); if (!completed) { TestRuntime.IgnoreInCI("Transient network failure - ignore in CI"); } Assert.IsTrue(completed, "Network request completed"); Assert.IsNull(ex, "Exception"); Assert.IsNotNull(nativeSetCookieResult, "Native set-cookies result"); Assert.IsNotNull(nativeCookieResult, "Native cookies result"); Assert.IsFalse(nativeCookieResult.Contains("chocolate-chip")); var cookiesFromServer = cookieContainer.GetCookies(new Uri(url)); Assert.AreEqual(0, cookiesFromServer.Count, "Cookies received from server."); }
public void TestNSUrlSessionHandlerCookieContainer() { var url = NetworkResources.Httpbin.CookiesUrl; var cookie = new Cookie("cookie", "chocolate-chip"); var cookieContainer = new CookieContainer(); cookieContainer.Add(new Uri(url), cookie); string managedCookieResult = null; string nativeCookieResult = null; Exception ex = null; var completed = false; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { try { var managedHandler = new HttpClientHandler() { AllowAutoRedirect = false, CookieContainer = cookieContainer, }; var managedClient = new HttpClient(managedHandler); var managedResponse = await managedClient.GetAsync(url); managedCookieResult = await managedResponse.Content.ReadAsStringAsync(); var nativeHandler = new NSUrlSessionHandler() { AllowAutoRedirect = true, CookieContainer = cookieContainer, }; var nativeClient = new HttpClient(nativeHandler); var nativeResponse = await nativeClient.GetAsync(url); nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync(); } catch (Exception e) { ex = e; } finally { completed = true; } }, () => completed); if (!completed || managedCookieResult.Contains("502 Bad Gateway") || nativeCookieResult.Contains("502 Bad Gateway")) { TestRuntime.IgnoreInCI("Transient network failure - ignore in CI"); } Assert.IsTrue(completed, "Network request completed"); Assert.IsNull(ex, "Exception"); Assert.IsNotNull(managedCookieResult, "Managed cookies result"); Assert.IsNotNull(nativeCookieResult, "Native cookies result"); Assert.AreEqual(managedCookieResult, nativeCookieResult, "Cookies"); }
public void TestNSUrlSessionHandlerCookies() { var managedCookieResult = false; var nativeCookieResult = false; Exception ex = null; var completed = false; IEnumerable <string> nativeCookies = null; IEnumerable <string> managedCookies = null; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { var url = NetworkResources.Httpbin.GetSetCookieUrl("cookie", "chocolate-chip"); try { var managedHandler = new HttpClientHandler() { AllowAutoRedirect = false, }; var managedClient = new HttpClient(managedHandler); var managedResponse = await managedClient.GetAsync(url); managedCookieResult = managedResponse.Headers.TryGetValues("Set-Cookie", out managedCookies); var nativeHandler = new NSUrlSessionHandler() { AllowAutoRedirect = false, }; nativeHandler.AllowAutoRedirect = true; var nativeClient = new HttpClient(nativeHandler); var nativeResponse = await nativeClient.GetAsync(url); nativeCookieResult = nativeResponse.Headers.TryGetValues("Set-Cookie", out nativeCookies); } catch (Exception e) { ex = e; } finally { completed = true; } }, () => completed); if (!completed) { TestRuntime.IgnoreInCI("Transient network failure - ignore in CI"); } Assert.IsTrue(completed, "Network request completed"); Assert.IsNull(ex, "Exception"); Assert.IsTrue(managedCookieResult, $"Failed to get managed cookies"); Assert.IsTrue(nativeCookieResult, $"Failed to get native cookies"); Assert.AreEqual(1, managedCookies.Count(), $"Managed Cookie Count"); Assert.AreEqual(1, nativeCookies.Count(), $"Native Cookie Count"); Assert.That(nativeCookies.First(), Does.StartWith("cookie=chocolate-chip;"), $"Native Cookie Value"); Assert.That(managedCookies.First(), Does.StartWith("cookie=chocolate-chip;"), $"Managed Cookie Value"); }
async Task Connect() { var config = NSUrlSessionConfiguration.DefaultSessionConfiguration; config.RequestCachePolicy = NSUrlRequestCachePolicy.ReloadIgnoringLocalCacheData; config.URLCache = null; /*config.TLSMinimumSupportedProtocol = Security.SslProtocol.Tls_1_2; * var cfNetwork = Dlfcn.dlopen (Constants.CFNetworkLibrary, 0); * var httpProxyHostKey = Dlfcn.GetStringConstant (cfNetwork, "kCFStreamPropertyHTTPProxyHost"); * var httpProxyPortKey = Dlfcn.GetStringConstant (cfNetwork, "kCFStreamPropertyHTTPProxyPort"); * var httpsProxyHostKey = Dlfcn.GetStringConstant (cfNetwork, "kCFStreamPropertyHTTPSProxyHost"); * var httpsProxyPortKey = Dlfcn.GetStringConstant (cfNetwork, "kCFStreamPropertyHTTPSProxyPort"); * var proxyHost = new NSString ("192.168.1.102"); * var proxyPort = new NSNumber (8888); * // Do any additional setup after loading the view. * var dictionary = new NSDictionary ( * "HTTPEnable", 1, * "HTTPSEnable", 1, * httpProxyHostKey, proxyHost, * httpProxyPortKey, proxyPort, * httpsProxyHostKey, proxyHost, * httpsProxyPortKey, proxyPort); * config.ConnectionProxyDictionary = dictionary;*/ //config.ConnectionProxyDictionary = dictionary; //config.URLCache.RemoveAllCachedResponses (); var handler = new NSUrlSessionHandler(config); handler.DisableCaching = true; handler.Credentials = new TestCredential(); var client = new HttpClient(handler); //string url = "https://www.google.co.uk"; string url = "https://api.nuget.org/v3/index.json"; //string url = "http://cambridge.org"; var request = new HttpRequestMessage(HttpMethod.Get, url); AddHeaders(request); var response = await client.SendAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("OK"); } else { Console.Write(response.StatusCode); } }
public HttpClient GetHttpClient() { var config = NSUrlSessionConfiguration.DefaultSessionConfiguration; config.TimeoutIntervalForRequest = 30; config.TimeoutIntervalForResource = 30; var handler = new NSUrlSessionHandler(config); var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10) }; client.DefaultRequestHeaders.Add("Accept", "application/json"); return(client); }
// // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); var iosClientHandler = new NSUrlSessionHandler(); //iosClientHandler.TrustOverride += (sender, trust) => //{ // return true; //}; Services.HttpClientService.HttpClientHandler = iosClientHandler; LoadApplication(new App()); return(base.FinishedLaunching(app, options)); }
// // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); var iosClientHandler = new NSUrlSessionHandler(); // yay! found a fix: https://github.com/xamarin/xamarin-macios/pull/6103/files iosClientHandler.TrustOverride += (sender, trust) => { return(true); }; App.HttpClientHandler = iosClientHandler; LoadApplication(new App()); return(base.FinishedLaunching(app, options)); }
public HttpClient GetHttpClient() { HttpClient httpClient; if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0)) { var handler = new NSUrlSessionHandler(); httpClient = new HttpClient(handler); } else { httpClient = new HttpClient(); } HttpClientConfig.ConfigureRequestHeadersAndSize(httpClient); return(httpClient); }
public HttpClient Client(TimeSpan?timeout = null) { var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration; configuration.TimeoutIntervalForRequest = timeout?.Seconds ?? 100; var handler = new NSUrlSessionHandler(configuration) { DisableCaching = true }; return(new HttpClient(handler) { DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"), Pragma = { NameValueHeaderValue.Parse("no-cache") } } }); }
// YP: Additional materials: // - Xamarin.iOS Certificate Pinning: https://nicksnettravels.builttoroam.com/ios-certificate/ // - NSUrlSessionHandler sources: https://github.com/xamarin/xamarin-macios/blob/edd8a2c8963063ca0ab3357e251944f4aa053fa8/src/Foundation/NSUrlSessionHandler.cs internal static HttpMessageHandler CreateHandler() { var nativeHandler = new NSUrlSessionHandler(); nativeHandler.TrustOverrideForUrl = (sender, url, trust) => { trust.Evaluate(out var error); if (error != null) { Console.WriteLine(error.UserInfo); } return(true); }; // also need ignore invalid SSL domain in info.plist (ATS) return(nativeHandler); }
public void TestNSUrlSessionDefaultDisabledCookies() { // simple test. send a request with a set-cookie url, get the data // and ensure that the second request does not send any cookies. var url = NetworkResources.Httpbin.GetSetCookieUrl("cookie", "chocolate-chip"); string nativeSetCookieResult = null; string nativeCookieResult = null; Exception ex = null; var completed = false; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { try { var nativeHandler = new NSUrlSessionHandler() { AllowAutoRedirect = true, UseCookies = false, }; var nativeClient = new HttpClient(nativeHandler); var nativeResponse = await nativeClient.GetAsync(url); nativeSetCookieResult = await nativeResponse.Content.ReadAsStringAsync(); // got the response, perofm a second queries to the cookies endpoint to get // the actual cookies sent from the storage nativeResponse = await nativeClient.GetAsync(NetworkResources.Httpbin.CookiesUrl); nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync(); } catch (Exception e) { ex = e; } finally { completed = true; } }, () => completed); Assert.IsNull(ex, "Exception"); Assert.IsNotNull(nativeSetCookieResult, "Native set-cookies result"); Assert.IsNotNull(nativeCookieResult, "Native cookies result"); Assert.IsFalse(nativeCookieResult.Contains("chocolate-chip")); }
public NSUrlSessionHandlerDelegate(NSUrlSessionHandler handler) { sessionHandler = handler; }
public void GHIssue8344() { var username = "******"; var password = "******"; var url = $"https://httpbin.org/basic-auth/{username}/{password}"; // perform two requests, one that will get a 200 with valid creds, one that wont and assert that // the second call does get a 401 // create a http client to use with some creds that we do know are not valid var firstHandler = new NSUrlSessionHandler() { Credentials = new NetworkCredential(username, password, "") }; var firstClient = new HttpClient(firstHandler); bool done = false; HttpStatusCode httpStatus = HttpStatusCode.NotFound; Exception ex = null; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { try { var result = await firstClient.GetAsync(url); httpStatus = result.StatusCode; } catch (Exception e) { ex = e; } finally { done = true; } }, () => done); if (!done) // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail { Assert.Inconclusive("First request timedout."); } else { Assert.IsNull(ex, "First request exception not null"); Assert.AreEqual(HttpStatusCode.OK, httpStatus, "First status not ok"); } // exactly same operation, diff handler, wrong password, should fail var secondHandler = new NSUrlSessionHandler() { Credentials = new NetworkCredential(username, password + password, "") }; var secondClient = new HttpClient(secondHandler); done = false; httpStatus = HttpStatusCode.NotFound; ex = null; TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => { try { var result = await secondClient.GetAsync(url); httpStatus = result.StatusCode; } catch (Exception e) { ex = e; } finally { done = true; } }, () => done); if (!done) // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail { Assert.Inconclusive("Second request timedout."); } else { Assert.IsNull(ex, "Second request exception not null"); Assert.AreEqual(HttpStatusCode.Unauthorized, httpStatus, "Second status not ok"); } }
public ClientJsonResponse(NSUrlSessionHandler handler, IStorage storage) : base(handler, storage) { managerMessageResponse = new ManagerHttpJsonResponse <T>(); }
public ClientFormUrlEncodeResponse(NSUrlSessionHandler handler, IStorage storage) : base(handler, storage) { managerMessageResponse = new ManagerHttpFormUrlEncode(); }
public HandlerWrapper(NSUrlSessionHandler handler) { this.handlerType = handler.GetType().Name; this.handler = new NSUrlSessionHandler(); }
static void AddFiddlerRootCertificate(NSUrlSessionHandler handler) { #if DEBUG //handler.AddTrustedCerts(FiddlerRootCertificateStream); // 添加https抓包调试用的证书,仅测试环境下 #endif }