Inheritance: System.Net.Http.HttpMessageHandler
        public async Task<bool> UploadBytes(string url, byte[] data)
        {
            try
            {
                if (_networkInformation.QuickNetworkCheck())
                {
                    var native = new NativeMessageHandler();

                    var httpClient = new HttpClient(native);
                    var message = new HttpRequestMessage(HttpMethod.Post, url);

                    native.RegisterForProgress(message, (bytes, totalBytes, expected) => new TransferProgressMessage(url, bytes, totalBytes, expected, true).Send());

                    var content = new ByteArrayContent(data);

                    message.Content = content;

                    var result = await httpClient.SendAsync(message);
                    return result.IsSuccessStatusCode;
                }
            }
            catch
            {
                Debug.WriteLine("WARNING: Could not upload: {0}", url);
            }

            return false;
        }
Example #2
0
        public Task GetAuthorizationToken()
        {
            return(new Task(() =>
            {
                var handler = new NativeMessageHandler();

                                #if __IOS__
                handler = new ModernHttpClient.NativeMessageHandler()
                {
                    Proxy = CoreFoundation.CFNetwork.GetDefaultProxy(),
                    UseProxy = true,
                };
                                #endif

                var client = new HttpClient(handler);
//				var token = JToken.FromObject(new
//				{
//					access_token = App.AuthToken
//				});

                var dict = new Dictionary <string, string>();
                dict.Add("access_token", App.AuthToken);

                var content = new FormUrlEncodedContent(dict);
                var response = client.PostAsync(Keys.AzureDomain + "/login/google", content).Result;
                var body = response.Content.ReadAsStringAsync().Result;

                Console.WriteLine(body);
            }));
        }
		//Using ModernHTTPClient
		private async Task<JsonValue> AnswerHttp(string question)
		{
			JsonValue jsonDoc = null;
			const string dataset = "travel";
			var questionJson = new JsonObject();
			questionJson.Add("questionText", question);
			var evidenceRequest = new JsonObject();
			evidenceRequest.Add("items", 1);
			questionJson.Add("evidenceRequest", evidenceRequest);
			var postData = new JsonObject();
			postData.Add("question", questionJson);

			string text = postData.ToString();
			var _nativehandler = new NativeMessageHandler ();

			using (var content = new StringContent(text, Encoding.UTF8, "application/json"))
			using (var client = new HttpClient(_nativehandler))
			{
			
				client.DefaultRequestHeaders.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", 
					Convert.ToBase64String(
						System.Text.ASCIIEncoding.ASCII.GetBytes(
							string.Format("{0}:{1}", username,password))));
				client.DefaultRequestHeaders.Accept.Add (new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue ("application/json"));
				var response = await client.PostAsync(baseURL, content).ConfigureAwait(false);
				if (response.IsSuccessStatusCode)
				{
					var jsonOut = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
					jsonDoc = await Task.Run (() => JsonObject.Parse (jsonOut));
				}
			}

			return jsonDoc;
		}
        public async Task<bool> UploadBytes(string url, byte[] data)
        {
            try
            {
                if (_networkInformation.QuickNetworkCheck())
                {
                    var h = new NativeMessageHandler();
                
                    var httpClient = new HttpClient(h);
                    var message = new HttpRequestMessage(HttpMethod.Post, url);

                    var content = new ByteArrayContent(data);

                    message.Content = content;

                    var result = await httpClient.SendAsync(message);
                    return result.IsSuccessStatusCode;
                }
            }
            catch
            {
                Debug.WriteLine("WARNING: Could not upload: {0}", url);
            }

            return false;
        }
		HttpClient CreateClient()
		{
			NativeCookieHandler cookieHandler = Settings.mNativeCookieHandler;//new NativeCookieHandler ();
			NativeMessageHandler handler = new NativeMessageHandler(true,true,cookieHandler){
				UseCookies = true,
			};
			return new HttpClient(handler);
		}
        async partial void doIt (Foundation.NSObject sender)
        {
            var handler = new NativeMessageHandler();
            var client = new HttpClient(handler);

            currentToken = new CancellationTokenSource();
            var st = new Stopwatch();

            st.Start();
            try {
                handler.DisableCaching = true;
                var url = "https://github.com/paulcbetts/ModernHttpClient/releases/download/0.9.0/ModernHttpClient-0.9.zip";
                url = "https://test.triplesport.net:4443/secure.txt";

                var request = new HttpRequestMessage(HttpMethod.Get, url);
                handler.RegisterForProgress(request, HandleDownloadProgress);

                //if using NTLM authentication pass the credentials below
                //handler.Credentials = new NetworkCredential("user","pass");

                resp = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, currentToken.Token);
                result.Text = "Got the headers!";

                Console.WriteLine("Status code: {0}", resp.StatusCode);

                Console.WriteLine("Reason: {0}", resp.ReasonPhrase);

                Console.WriteLine("Headers");
                foreach (var v in resp.Headers) {
                    Console.WriteLine("{0}: {1}", v.Key, String.Join(",", v.Value));
                }

                Console.WriteLine("Content Headers");
                foreach (var v in resp.Content.Headers) {
                    Console.WriteLine("{0}: {1}", v.Key, String.Join(",", v.Value));
                }

                var bytes = await resp.Content.ReadAsByteArrayAsync();
                result.Text = String.Format("Read {0} bytes", bytes.Length);

                var md5 = MD5.Create();
                var md5Result = md5.ComputeHash(bytes);
                md5sum.Text = ToHex(md5Result, false);
            } catch (Exception ex) {
                result.Text = ex.ToString();
            } finally {
                st.Stop();
                result.Text = (result.Text ?? "") + String.Format("\n\nTook {0} milliseconds", st.ElapsedMilliseconds);
            }
        }
        async partial void doIt (MonoTouch.Foundation.NSObject sender)
        {
            var handler = new NativeMessageHandler();
            var client = new HttpClient(handler);

            currentToken = new CancellationTokenSource();
            var st = new Stopwatch();

            st.Start();
            try {
                var url = "https://github.com/paulcbetts/ModernHttpClient/releases/download/0.9.0/ModernHttpClient-0.9.zip";
                //var url = "https://github.com/downloads/nadlabak/android/cm-9.1.0a-umts_sholes.zip";

                var request = new HttpRequestMessage(HttpMethod.Get, url);
                handler.RegisterForProgress(request, HandleDownloadProgress);

                resp = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, currentToken.Token);
                result.Text = "Got the headers!";

                Console.WriteLine("Headers");
                foreach (var v in resp.Headers) {
                    Console.WriteLine("{0}: {1}", v.Key, String.Join(",", v.Value));
                }

                Console.WriteLine("Content Headers");
                foreach (var v in resp.Content.Headers) {
                    Console.WriteLine("{0}: {1}", v.Key, String.Join(",", v.Value));
                }

                var bytes = await resp.Content.ReadAsByteArrayAsync();
                result.Text = String.Format("Read {0} bytes", bytes.Length);

                var md5 = MD5.Create();
                var md5Result = md5.ComputeHash(bytes);
                md5sum.Text = ToHex(md5Result, false);
            } catch (Exception ex) {
                result.Text = ex.ToString();
            } finally {
                st.Stop();
                result.Text = (result.Text ?? "") + String.Format("\n\nTook {0} milliseconds", st.ElapsedMilliseconds);
            }
        }
        public async Task<byte[]> DownloadBytes(string url)
        {
            try
            {
                if (_networkInformation.QuickNetworkCheck())
                {
                    var native = new NativeMessageHandler();
                    var httpClient = new HttpClient(native);
                    var message = new HttpRequestMessage(HttpMethod.Get, url);

                    native.RegisterForProgress(message, (bytes, totalBytes, expected) => new TransferProgressMessage(url, bytes, totalBytes, expected, false).Send());

                    var result = await httpClient.SendAsync(message);

                    if (result.IsSuccessStatusCode)
                    {
                        var content = result.Content;
                        using (var s = await content.ReadAsStreamAsync())
                        {
                            if (s != null)
                            {
                                using (var ms = new MemoryStream())
                                {
                                    await s.CopyToAsync(ms);
                                    return ms.ToArray();
                                }
                            }
                        }
                    }


                }
            }
            catch
            {
                Debug.WriteLine("WARNING: Could not download: {0}", url);
            }

            return null;
        }
        async Task<IHttpTransferResult> _doDownload(DownloadQueueObject obj, IHttpTransferConfig downloadConfig)
        {
            // add support for Gzip decompression
            var native = new NativeMessageHandler();
            
            var httpClient = new HttpClient(native);

            using (httpClient)
            {
                var method = HttpMethod.Get;

                switch (obj.Verb)
                {
                    case "GET":
                        method = HttpMethod.Get;
                        break;
                    case "POST":
                        method = HttpMethod.Post;
                        break;
                    case "PUT":
                        method = HttpMethod.Put;
                        break;
                    case "DELETE":
                        method = HttpMethod.Delete;
                        break;
                }

                using (var message = new HttpRequestMessage(method, obj.Url))
                {

                    native.RegisterForProgress(message, (bytes, totalBytes, expected) => new TransferProgressMessage(obj.Url, bytes, totalBytes, expected, downloadConfig.Verb.ToLower() != "get").Send());

                    if (downloadConfig.Headers != null)
                    {
                        foreach (var item in downloadConfig.Headers)
                        {
                            message.Headers.Add(item.Key, item.Value);
                        }
                    }

                    // Accept-Encoding:
                    if (downloadConfig.AcceptEncoding != null)
                    {
                        //message.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue(""));
                        message.Headers.Add("Accept-Encoding", downloadConfig.AcceptEncoding);
                    }


                    // Accept:
                    if (!string.IsNullOrWhiteSpace(downloadConfig.Accept))
                    {
                        message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(downloadConfig.Accept));
                    }


                    if (!string.IsNullOrWhiteSpace(obj.Data))
                    {
                        var content = new StringContent(obj.Data, Encoding.UTF8,
                            downloadConfig.ContentEncoding ?? "application/json");
                        message.Content = content;
                    }

                    if (obj.ByteData != null)
                    {
                        var content = new ByteArrayContent(obj.ByteData, 0, obj.ByteData.Length);

                        message.Content = content;
                    }

                    if (downloadConfig.Auth != null && downloadConfig.AuthScheme != null)
                    {
                        message.Headers.Authorization = new AuthenticationHeaderValue(downloadConfig.AuthScheme,
                            downloadConfig.Auth);
                    }

                    try
                    {
                        Debug.WriteLine("{0}: {1}", downloadConfig.Verb.ToLower() == "get" ? "Downloading" : "Uploading", obj.Url);

                        using (var result = await httpClient.SendAsync(message))
                        {
                            Debug.WriteLine("Finished: {0}", obj.Url);
                            return await _httpTransferService.GetResult(result, downloadConfig);
                        }



                    }
                    catch (HttpRequestException ex)
                    {
                        Debug.WriteLine("Warning - HttpRequestException encountered: {0}", ex.Message);

                        return _httpTransferService.GetExceptionResult(ex,
                            "XamlingCore.Portable.Net.Downloaders.HttpClientDownloader", downloadConfig);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Warning - general HTTP exception encountered: {0}", ex.Message);
                        return _httpTransferService.GetExceptionResult(ex,
                            "XamlingCore.Portable.Net.Downloaders.HttpClientDownloader", downloadConfig);
                    }
                }
            }


        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            //This API is only available in Mono and Xamarin products.
            //You can filter and/or re-order the ciphers suites that the SSL/TLS server will accept from a client.
            //The following example removes weak (export) ciphers from the list that will be offered to the server.
            ServicePointManager.ClientCipherSuitesCallback += (protocol, allCiphers) =>
                allCiphers.Where(x => !x.Contains("EXPORT")).ToList();

            //Here we accept any certificate and just print the cert's data.
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => {
                System.Diagnostics.Debug.WriteLine("Callback Server Certificate: " + sslPolicyErrors);

                foreach(var el in chain.ChainElements) {
                    System.Diagnostics.Debug.WriteLine(el.Certificate.GetCertHashString());
                    System.Diagnostics.Debug.WriteLine(el.Information);
                }

                return true;
            };

            // Get our button from the layout resource,
            // and attach an event to it
            var button = FindViewById<Button>(Resource.Id.doIt);
            var cancel = FindViewById<Button>(Resource.Id.cancelButton);
            var result = FindViewById<TextView>(Resource.Id.result);
            var hashView = FindViewById<TextView>(Resource.Id.md5sum);
            var status = FindViewById<TextView>(Resource.Id.status);
            progress = FindViewById<ProgressBar>(Resource.Id.progress);

            var resp = default(HttpResponseMessage);

            cancel.Click += (o, e) => {
                Console.WriteLine("Canceled token {0:x8}", this.currentToken.Token.GetHashCode());
                this.currentToken.Cancel();
                if (resp != null) resp.Content.Dispose();
            };

            button.Click += async (o, e) => {
                var handler = new NativeMessageHandler();
                var client = new HttpClient(handler);

                currentToken = new CancellationTokenSource();
                var st = new Stopwatch();

                st.Start();
                try {
                    var url = "https://tv.eurosport.com";
                    //var url = "https://github.com/downloads/nadlabak/android/cm-9.1.0a-umts_sholes.zip";
                    //var url = "https://github.com/paulcbetts/ModernHttpClient/releases/download/0.9.0/ModernHttpClient-0.9.zip";

                    var request = new HttpRequestMessage(HttpMethod.Get, url);
                    handler.RegisterForProgress(request, HandleDownloadProgress);

                    resp = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, currentToken.Token);
                    result.Text = "Got the headers!";

                    status.Text = string.Format("HTTP {0}: {1}", (int)resp.StatusCode, resp.ReasonPhrase);

                    foreach (var v in resp.Headers) {
                        Console.WriteLine("{0}: {1}", v.Key, String.Join(",", v.Value));
                    }

                    var stream = await resp.Content.ReadAsStreamAsync();

                    var ms = new MemoryStream();
                    await stream.CopyToAsync(ms, 4096, currentToken.Token);
                    var bytes = ms.ToArray();

                    result.Text = String.Format("Read {0} bytes", bytes.Length);

                    var md5 = MD5.Create();
                    var hash = md5.ComputeHash(bytes);
                    hashView.Text = ToHex(hash, false);
                } catch (Exception ex) {
                    result.Text = ex.ToString();
                } finally {
                    st.Stop();
                    result.Text = (result.Text ?? "") + String.Format("\n\nTook {0} milliseconds", st.ElapsedMilliseconds);
                }
            };
        }
		protected async Task ExecuteLoginCommand()
		{
			Error = string.Empty;

			if (Username.Equals(string.Empty) || Password.Equals(string.Empty)) {
				Error = Settings.MSG_EMPTY_USERNAME_OR_PWD;
				return;
			}

			if (isLoading)
				return;

			IsLoading = true;
			Info = "We're processing...";

			Settings.UseTreeMenu = UseTreeMenu;

			try {
				var content = new FormUrlEncodedContent (new[] {
					new KeyValuePair<string, string> (Settings.WP_USERNAME_FIELD, Username),
					new KeyValuePair<string, string> (Settings.WP_PWD_FIELD, Password)
				});

				NativeCookieHandler cookieHandler = Settings.mNativeCookieHandler;//new NativeCookieHandler ();
				NativeMessageHandler handler = new NativeMessageHandler(true,true,cookieHandler){
					UseCookies = true,
				};

				handler.AllowAutoRedirect = false;
				HttpClient client = new HttpClient (handler);

				HttpResponseMessage response =  await client.PostAsync (Settings.LoginUrl, content);

				if (response.StatusCode == HttpStatusCode.Redirect) {
					Debug.WriteLine("Redirect: " + response.ToString());
					Settings.wpLoggedIn = true;
					Settings.wpUsername = Username;
					Settings.wpPassword = Password;
				} else {
					string resultContent = await response.Content.ReadAsStringAsync ();

					response.EnsureSuccessStatusCode ();
					string responseUri = response.RequestMessage.RequestUri.ToString ();
					Debug.WriteLine (responseUri);
					Debug.WriteLine(resultContent);
					if (Settings.LoginUrl.ToLower ().Equals (responseUri.ToLower ())) {
						//login failed
						Error = Settings.MSG_INVALID_USERNAME_OR_PWD;
					} else {
						Settings.wpLoggedIn = true;
						Settings.wpUsername = Username;
						Settings.wpPassword = Password;
					}
				}

				if (Settings.wpLoggedIn) {
					if (Settings.CHECK_UPDATE) {
						var buildDetail = Mvx.Resolve<IBuildDetails>();
						var respUpdate = await Service.GetUpdate(new RequestUpdate(buildDetail.OS, buildDetail.VersionCode));
						if (respUpdate.Update_info != null) {
							Settings.UpdateInfo = respUpdate;
							IsLoading = false;
							return;
						}

						System.Diagnostics.Debug.WriteLine("Build detail os={0} version_code={1}", buildDetail.OS, buildDetail.VersionCode);
					}
					//go to profile to get more cookies
					response = await client.GetAsync(Settings.ProfileUrl);

					//get user info and gen cookie for json api auth controller
					var retAuth = await Service.GenrateAuthCookie();

					if (retAuth != null) {
						Settings.WP_AuthCookie = retAuth;
					} else {
						Settings.WP_AuthCookie = null;
					}
				}
			} catch (Exception e ){
				Error = Settings.MSG_NETWORK_COMMON;
				#if DEBUG
				System.Diagnostics.Debug.WriteLine("Login Error: " + e.Message);
				Error += e.ToString();
				#endif
			}				


			Info = string.Empty;
			IsLoading = false;
		}
 public HostnameVerifier(NativeMessageHandler handler)
 {
     this.nativeHandler = handler;
 }
Example #13
0
		public Task GetAuthorizationToken()
		{
			return new Task(() =>
			{
				var handler = new NativeMessageHandler();

				#if __IOS__
				handler = new ModernHttpClient.NativeMessageHandler() {
					Proxy = CoreFoundation.CFNetwork.GetDefaultProxy(),
					UseProxy = true,
				};
				#endif

				var client = new HttpClient(handler);
//				var token = JToken.FromObject(new
//				{
//					access_token = App.AuthToken
//				});

				var dict = new Dictionary<string, string>();
				dict.Add("access_token", App.AuthToken);

				var content = new FormUrlEncodedContent(dict);
				var response = client.PostAsync(Keys.AzureDomain + "/login/google", content).Result;
				var body = response.Content.ReadAsStringAsync().Result;

				Console.WriteLine(body);


			});
		}
 public DataTaskDelegate(NativeMessageHandler handler)
 {
     this.nativeHandler = handler;
 }
Example #15
0
        public ModernHttpClient()
        {
            var handler = new NativeMessageHandler();

            var httpClient = new System.Net.Http.HttpClient(handler);
        }
 public DataTaskDelegate(NativeMessageHandler that)
 {
     this.This = that;
 }
Example #17
0
 public DataTaskDelegate(NativeMessageHandler that)
 {
     this.This = that;
 }