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);
        }
        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);
        }
예제 #5
0
        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();

                client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("ModernHttpClient", "1.0"));
                client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("MyTest", "2.0"));
                handler.DisableCaching = true;

                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);
                }
            };
        }
        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));
                    }
                }
            }
        }