protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url = new Java.Net.URL(java_uri);

            var body = default(RequestBody);
            if (request.Content != null) {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                body = RequestBody.Create(MediaType.Parse(request.Content.Headers.ContentType.MediaType), bytes);
            }

            var builder = new Request.Builder()
                .Method(request.Method.Method.ToUpperInvariant(), body)
                .Url(url);

            var keyValuePairs = request.Headers
                .Union(request.Content != null ?
                    (IEnumerable<KeyValuePair<string, IEnumerable<string>>>)request.Content.Headers :
                    Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>());

            foreach (var kvp in keyValuePairs) builder.AddHeader(kvp.Key, String.Join(",", kvp.Value));

            cancellationToken.ThrowIfCancellationRequested();

            var rq = builder.Build();
            var call = client.NewCall(rq);
            cancellationToken.Register(() => call.Cancel());

            var resp = default(Response);
            try {
                resp = await call.EnqueueAsync().ConfigureAwait(false);
            } catch (IOException ex) {
                if (ex.Message.ToLowerInvariant().Contains("canceled")) {
                    throw new OperationCanceledException();
                }

                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());
            if (respBody != null) {
                var content = new ProgressStreamContent(respBody.ByteStream(), cancellationToken);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content = content;
            } else {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();
            foreach (var k in respHeaders.Names()) {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return ret;
        }
Exemple #2
0
        public static async Task <List <Bitmap> > GetBackdrop(string movieID, string type)
        {
            string key = "253ceb1e198e26b094348524da5bc8ab";

            string query = string.Format("https://api.themoviedb.org/3/{0}/{1}?api_key={2}", type, movieID, key);

            var result = downloadjson.getJson(query);

            List <Bitmap> photob = new List <Bitmap>();
            Bitmap        ph     = null;

            try
            {
                Java.Net.URL link1 = new Java.Net.URL("http://image.tmdb.org/t/p/w780/" + result["backdrop_path"].ToString());
                await Task.Run(() => { ph = BitmapFactory.DecodeStream(link1.OpenStream()); });

                photob.Add(ph);
            }
            catch (Exception ex) {
            }


            try
            {
                Java.Net.URL link2 = new Java.Net.URL("http://image.tmdb.org/t/p/w185/" + result["poster_path"].ToString());
                await Task.Run(() => { ph = BitmapFactory.DecodeStream(link2.OpenStream()); });

                photob.Add(ph);
                return(photob);
            }
            catch (Exception ex) {}
            return(photob);
        }
Exemple #3
0
        public Drawable GetDrawable(string source)
        {
            Drawable drawable;
            Bitmap   bitMap;

            BitmapFactory.Options bitMapOption;
            try
            {
                bitMapOption = new BitmapFactory.Options();
                bitMapOption.InJustDecodeBounds = false;
                bitMapOption.InPreferredConfig  = Bitmap.Config.Argb4444;
                bitMapOption.InPurgeable        = true;
                bitMapOption.InInputShareable   = true;
                var url = new Java.Net.URL(source);

                bitMap   = BitmapFactory.DecodeStream(url.OpenStream(), null, bitMapOption);
                drawable = new BitmapDrawable(bitMap);
                //var url = new Java.Net.URL(source);
                //drawable =  Drawable.CreateFromStream(url.OpenStream(), null);
            }
            catch (Exception ex)
            {
                return(null);
            }

            drawable.SetBounds(0, 0, bitMapOption.OutWidth, bitMapOption.OutHeight);
            return(drawable);
        }
Exemple #4
0
        /// <summary>
        /// This junit does not work because of a problem? in URL: The hashcode of
        /// the 2 urls url1 & url2 are equal! even if theu point to different domains
        /// (having the same IP)
        /// </summary>
        /// <exception cref="System.Exception">System.Exception</exception>
        public virtual void TestURL()
        {
            Java.Net.URL url1 = new Java.Net.URL("http://wiki.neodatis.org");
            Java.Net.URL url2 = new Java.Net.URL("http://www.neodatis.org");
            object       o1   = url1.GetContent();
            object       o2   = url2.GetContent();
            int          h1   = url1.GetHashCode();
            int          h2   = url2.GetHashCode();

            Println(h1 + " - " + h2);
            Println(url1.GetHost() + " - " + url1.GetDefaultPort() + " - " + url1.GetFile() +
                    " - " + url1.GetRef());
            Println(url2.GetHost() + " - " + url2.GetDefaultPort() + " - " + url2.GetFile() +
                    " - " + url2.GetRef());
            Println(url1.GetHost().GetHashCode() + " - " + url1.GetDefaultPort() + " - " + url1
                    .GetFile().GetHashCode() + " - " + url1.GetRef());
            Println(url2.GetHost().GetHashCode() + " - " + url2.GetDefaultPort() + " - " + url2
                    .GetFile().GetHashCode() + " - " + url2.GetRef());
            NeoDatis.Odb.ODB odb = Open(Name);
            odb.Store(url1);
            odb.Store(url2);
            odb.Close();
            odb = Open(Name);
            NeoDatis.Odb.Objects l = odb.GetObjects(typeof(Java.Net.URL));
            odb.Close();
            if (testNewFeature)
            {
                AssertEquals("Same HashCode Problem", 2, l.Count);
            }
        }
Exemple #5
0
        public virtual void Test22URL()
		{
			Java.Net.URL url1 = new Java.Net.URL("http://wiki.neodatis.org");
			Java.Net.URL url2 = new Java.Net.URL("http://www.neodatis.org");
			object o1 = url1.GetContent();
			object o2 = url2.GetContent();
			int h1 = url1.GetHashCode();
			int h2 = url2.GetHashCode();
			Println(h1 + " - " + h2);
			Println(url1.GetHost() + " - " + url1.GetDefaultPort() + " - " + url1.GetFile() +
				 " - " + url1.GetRef());
			Println(url2.GetHost() + " - " + url2.GetDefaultPort() + " - " + url2.GetFile() +
				 " - " + url2.GetRef());
			Println(url1.GetHost().GetHashCode() + " - " + url1.GetDefaultPort() + " - " + url1
				.GetFile().GetHashCode() + " - " + url1.GetRef());
			Println(url2.GetHost().GetHashCode() + " - " + url2.GetDefaultPort() + " - " + url2
				.GetFile().GetHashCode() + " - " + url2.GetRef());
			NeoDatis.Odb.ODB odb = Open(Name);
			odb.Store(url1);
			odb.Store(url2);
			odb.Close();
			odb = Open(Name);
			NeoDatis.Odb.Objects l = odb.GetObjects(typeof(Java.Net.URL));
			odb.Close();
			if (testNewFeature)
			{
				AssertEquals("Same HashCode Problem", 2, l.Count);
			}
		}
 void TestUrlConnectionStream(TextView textview)
 {
     Java.Net.URL           url           = new Java.Net.URL("http://www.google.pt/logos/classicplus.png");
     Java.Net.URLConnection urlConnection = url.OpenConnection();
     Android.Graphics.BitmapFactory.DecodeStream(urlConnection.InputStream);
     textview.Text += "\n\nOpened Url connection stream and loaded image";
 }
Exemple #7
0
        public static async Task <CastDetails> GetSeasons(string movieID, string season)
        {
            string key = "253ceb1e198e26b094348524da5bc8ab";

            string query = string.Format("https://api.themoviedb.org/3/tv/{0}/season/{1}?api_key={2}&language=en-US", movieID, season, key);

            var result = downloadjson.getJson(query);

            CastDetails currentPerson = null;


            //create new object
            currentPerson = new CastDetails();
            try
            {
                currentPerson.Name = result["name"].ToString();
                currentPerson.ID   = result["id"].ToString();
            }
            catch (Exception ex) { }


            try
            {
                Java.Net.URL link2 = new Java.Net.URL("http://image.tmdb.org/t/p/w185/" + result["poster_path"].ToString());
                await Task.Run(() => { currentPerson.profile_path = BitmapFactory.DecodeStream(link2.OpenStream()); });
            }
            catch (Exception ex) { }

            return(currentPerson);
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url = new Java.Net.URL(java_uri);
            Java.Net.HttpURLConnection rq;
            try {
                rq = client.Open(url);
            } catch(Java.Net.UnknownHostException e) {
                throw new WebException("Name resolution failure", e, WebExceptionStatus.NameResolutionFailure, null);
            }
            rq.RequestMethod = request.Method.Method.ToUpperInvariant();

            foreach (var kvp in request.Headers) { rq.SetRequestProperty(kvp.Key, kvp.Value.FirstOrDefault()); }

            if (request.Content != null) {
                foreach (var kvp in request.Content.Headers) { rq.SetRequestProperty (kvp.Key, kvp.Value.FirstOrDefault ()); }

                await Task.Run(async () => {
                    var contentStream = await request.Content.ReadAsStreamAsync().ConfigureAwait(false);
                    await copyToAsync(contentStream, rq.OutputStream, cancellationToken).ConfigureAwait(false);
                }, cancellationToken).ConfigureAwait(false);

                rq.OutputStream.Close();
            }

            return await Task.Run (() => {
                // NB: This is the line that blocks until we have headers
                var ret = new HttpResponseMessage((HttpStatusCode)rq.ResponseCode);

                // Test to see if we're being redirected (i.e. in a captive network)
                if (throwOnCaptiveNetwork && (url.Host != rq.URL.Host)) {
                    throw new WebException("Hostnames don't match, you are probably on a captive network");
                }

                cancellationToken.ThrowIfCancellationRequested();

                ret.Content = new StreamContent(new ConcatenatingStream(new Func<Stream>[] {
                    () => ret.IsSuccessStatusCode ? rq.InputStream : new MemoryStream(),
                    () => rq.ErrorStream ?? new MemoryStream (),
                }, true));

                var keyValuePairs = rq.HeaderFields.Keys
                    .Where(k => k != null)      // Yes, this happens. I can't even. 
                    .SelectMany(k => rq.HeaderFields[k]
                        .Select(val => new { Key = k, Value = val }));

                foreach (var v in keyValuePairs) {
                    ret.Headers.TryAddWithoutValidation(v.Key, v.Value);
                    ret.Content.Headers.TryAddWithoutValidation(v.Key, v.Value);
                }

                cancellationToken.Register (ret.Content.Dispose);

                ret.RequestMessage = request;
                return ret;
            }, cancellationToken).ConfigureAwait(false);
        }
            private static Bitmap DownloadImage(string url, string uid)
            {
                Bitmap imageBitmap = null;

                try
                {
                    byte[] imageBytes;
                    using (var mstream = new MemoryStream())
                    {
                        using (var imageUrl = new Java.Net.URL(url))
                        {
                            var options = new BitmapFactory.Options
                            {
                                InSampleSize = 1,
                                InPurgeable  = true
                            };

                            var bit = BitmapFactory.DecodeStream(imageUrl.OpenStream(), null, options);
                            bit.Compress(Bitmap.CompressFormat.Jpeg, 70, mstream);
                        }
                        imageBytes = mstream.ToArray();
                        System.IO.File.WriteAllBytes(System.IO.Path.Combine(baseDir, uid), imageBytes);
                        if (imageBytes != null && imageBytes.Length > 0)
                        {
                            var options = new BitmapFactory.Options
                            {
                                InJustDecodeBounds = true,
                            };
                            // BitmapFactory.DecodeResource() will return a non-null value; dispose of it.
                            using (var dispose = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length))
                            {
                            }
                            var imageHeight  = options.OutHeight;
                            var imageWidth   = options.OutWidth;
                            var imageType    = options.OutMimeType;
                            var height       = (float)options.OutHeight;
                            var width        = (float)options.OutWidth;
                            var inSampleSize = 1D;

                            if (height > 100 || width > 100)
                            {
                                inSampleSize = width > height
                                                    ? height / 100
                                                    : width / 100;
                            }
                            options.InSampleSize       = (int)inSampleSize;
                            options.InJustDecodeBounds = false;
                            return(BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length, options));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteLine(LogPriority.Error, "GetImageFromBitmap Error", ex.Message);
                }
                return(imageBitmap);
            }
Exemple #10
0
        private async Task <string> DownloadFile(string url)
        {
            string path = string.Empty;

            try
            {
                var fileName = GetFileName(url);
                path = System.IO.Path.Combine(Path, fileName);

                int totalBytes = GetFileSize(url);

                using (var fileUrl = new Java.Net.URL(url))
                {
                    using (var stream = fileUrl.OpenStream())
                    {
                        byte[] bytes          = new byte[totalBytes];
                        int    numBytesToRead = totalBytes;
                        int    numBytesRead   = 0;

                        while (numBytesToRead > 0)
                        {
                            // Read may return anything from 0 to numBytesToRead.
                            int n = await stream.ReadAsync(bytes, numBytesRead, numBytesToRead);

                            // Break when the end of the file is reached.
                            if (n == 0)
                            {
                                //await Task.Yield();
                                break;
                            }

                            numBytesRead   += n;
                            numBytesToRead -= n;

                            float percentage = (float)numBytesRead / (float)totalBytes;

                            var message = new DownloadProgressMessage()
                            {
                                Percentage = percentage
                            };

                            MessagingCenter.Send <DownloadProgressMessage>(message, "DownloadProgressMessage");
                        }

                        File.WriteAllBytes(path, bytes);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine(LogPriority.Error, "GetImageFromBitmap Error", ex.Message);
            }

            return(path);
        }
Exemple #11
0
 public static void SetDownloadedImageAsBackground(string urloftheimage)
 {
     ThreadPool.QueueUserWorkItem(async m =>
     {
         var inputStream = new Java.Net.URL(urloftheimage).OpenStream();
         var photograph  = await BitmapFactory.DecodeStreamAsync(inputStream);
         WallpaperManager wallpaperManager = WallpaperManager.GetInstance(Application.Context);
         wallpaperManager.SetBitmap(photograph);
     }
                                  );
 }
Exemple #12
0
            protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
            {
                Java.Net.URL url;
                try
                {
                    url         = new Java.Net.URL(_imageSource);
                    BitMapShown = Android.Graphics.BitmapFactory.DecodeStream(url.OpenConnection().InputStream);
                }
                catch (Exception ignored)
                {
                    Android.Util.Log.Error(TAG, "Exception", ignored);
                }

                return(BitMapShown);
            }
        private void LoadImage(ImageView logo, string logoUrl)
        {
            Bitmap bitImage = null;

            try
            {
                Stream inputStream = new Java.Net.URL(logoUrl).OpenStream();
                bitImage = BitmapFactory.DecodeStream(inputStream);

                logo.SetImageBitmap(bitImage);
            }
            catch (System.Exception ex)
            {
                var err = ex.Message;
            }
        }
Exemple #14
0
            protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
            {
                string urldisplay = @params[0].ToString();
                Bitmap mIcon11    = null;

                try
                {
                    var stream = new Java.Net.URL(urldisplay).OpenStream();
                    mIcon11 = BitmapFactory.DecodeStream(stream);
                }
                catch (System.Exception e)
                {
                    Log.Error($"{ResourcesTexts.Error}", e.Message);
                }
                return(mIcon11);
            }
Exemple #15
0
        static bool Download(Uri uri, string target)
        {
            var buffer = new byte[4 * 1024];

            try
            {               // use Java.Net.URL instead of WebClient...
                var tmpfile  = target + ".tmp";
                var imageUrl = new Java.Net.URL(uri.AbsoluteUri);
                var stream   = imageUrl.OpenStream();
                LogDebug("====== open " + ImageName(uri.AbsoluteUri));
                using (var o = File.Open(tmpfile, FileMode.OpenOrCreate)) {
                    byte[] buf = new byte[1024];
                    int    r;
                    while ((r = stream.Read(buf, 0, buf.Length)) > 0)
                    {
                        o.Write(buf, 0, r);
                    }
                }

                //using (var file = new FileStream(tmpfile, FileMode.Create, FileAccess.Write, FileShare.Read))
                //{
                //var req = WebRequest.Create(uri) as HttpWebRequest;

                //using (var resp = req.GetResponse())
                //{
                //    using (var s = resp.GetResponseStream())
                //    {
                //        int n;
                //        while ((n = s.Read(buffer, 0, buffer.Length)) > 0)
                //        {
                //            file.Write(buffer, 0, n);
                //        }
                //    }
                //}
                //}
                if (!File.Exists(target))                   // we're never updating images if they change, to reduce Exceptions and speed up
                {
                    File.Move(tmpfile, target);
                }
                return(true);
            }
            catch (Exception e)
            {
                LogDebug(String.Format("Problem with {0} {1}", uri, e.Message));
                return(false);
            }
        }
        private Bitmap GetImageBitmapFromUrl(String url)
        {
            Bitmap bm = null;

            Java.Net.URL aURL = new Java.Net.URL(url);
            Java.Net.HttpURLConnection conn = (Java.Net.HttpURLConnection)aURL.OpenConnection();
            conn.Connect();

            Stream         stream = conn.InputStream;
            BufferedStream bsteam = new BufferedStream(stream);

            bm = BitmapFactory.DecodeStream(bsteam);
            bsteam.Close();
            stream.Close();

            return(bm);
        }
        internal void SetVideoThumbnail(string url, CancellationToken cancellationToken)
        {
            _icon.SetImageResource(Resource.Drawable.placeholder);
            Bitmap imageSource = null;

            Task.Run(() =>
            {
                var imageStream = new Java.Net.URL(url).OpenStream();
                imageSource     = BitmapFactory.DecodeStream(imageStream);
            }).ContinueWith(t =>
            {
                if (t.Status == TaskStatus.RanToCompletion && !cancellationToken.IsCancellationRequested)
                {
                    _icon.SetImageBitmap(imageSource);
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemple #18
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View view = convertView; // re-use an existing view, if one is available

            if (view == null)        // otherwise create a new one
            {
                view = _context.LayoutInflater.Inflate(Android.Resource.Layout.ActivityListItem, null);
            }
            view.FindViewById <TextView>(Android.Resource.Id.Text1).Text = _items[position].Text;

            var imageUrl = new Java.Net.URL(_items[position].User.ProfileImageUrl);

            Task.Factory.StartNew(() =>
            {
                System.IO.Stream stream = imageUrl.OpenStream();
                var bitmap = Android.Graphics.BitmapFactory.DecodeStream(stream);
                (view.FindViewById <ImageView>(Android.Resource.Id.Icon)).SetImageBitmap(bitmap);
            });
            return(view);
        }
        private void LoadImageInBackground(ImageView imageView, string url, CancellationToken cancellationToken)
        {
            Bitmap imageSource = null;

            if (PlaceholderImageResource.HasValue)
            {
                imageView.SetImageResource(PlaceholderImageResource.Value);
            }
            Task.Run(() =>
            {
                var imageStream = new Java.Net.URL(url).OpenStream();
                imageSource     = BitmapFactory.DecodeStream(imageStream);
            }).ContinueWith(t =>
            {
                if (t.Status == TaskStatus.RanToCompletion && !cancellationToken.IsCancellationRequested)
                {
                    imageView.SetImageBitmap(imageSource);
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemple #20
0
        public static async Task <MovieDetails> GetBasicInfo(string movieID, string type)
        {
            string key = "253ceb1e198e26b094348524da5bc8ab";

            string query = string.Format("https://api.themoviedb.org/3/{0}/{1}?api_key={2}", type, movieID, key);

            var result = downloadjson.getJson(query);

            MovieDetails current = null;

            if (type == "movie")
            {
                //create new object
                current = new MovieDetails();
                try { current.title = result["original_title"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); };
                try { current.ID = (int)result["id"]; } catch (Exception ex) { Console.Write(ex.ToString()); }
                try
                {
                    Java.Net.URL link2 = new Java.Net.URL("http://image.tmdb.org/t/p/w185/" + result["poster_path"].ToString());
                    await Task.Run(() => { current.poster = BitmapFactory.DecodeStream(link2.OpenStream()); });
                }
                catch (Exception ex) { Console.Write(ex.ToString()); }
            }
            else if (type == "tv")
            {
                //create new object
                current = new MovieDetails();
                try { current.title = result["name"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); };
                try { current.ID = (int)result["id"]; } catch (Exception ex) { Console.Write(ex.ToString()); }
                try
                {
                    Java.Net.URL link2 = new Java.Net.URL("http://image.tmdb.org/t/p/w185/" + result["poster_path"].ToString());
                    await Task.Run(() => { current.poster = BitmapFactory.DecodeStream(link2.OpenStream()); });
                }
                catch (Exception ex) { Console.Write(ex.ToString()); }
            }


            return(current);
        }
Exemple #21
0
        private int GetFileSize(string fileUrl)
        {
            using (var url = new Java.Net.URL(fileUrl))
            {
                Java.Net.HttpURLConnection conn = null;
                try
                {
                    conn = (Java.Net.HttpURLConnection)url.OpenConnection();
                    conn.RequestMethod = "HEAD";

                    return(conn.ContentLength);
                }
                catch (Java.IO.IOException e)
                {
                    return(-1);
                }
                finally
                {
                    conn.Disconnect();
                }
            }
        }
        protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
        {
            string nodeResponse = "";

            try
            {
                var localNodeServer = new Java.Net.URL("http://localhost:3000/");
                var input           = new BufferedReader(
                    new InputStreamReader(localNodeServer.OpenStream()));
                String inputLine;
                while ((inputLine = input.ReadLine()) != null)
                {
                    nodeResponse = nodeResponse + inputLine;
                }
                input.Close();
            }
            catch (Exception ex)
            {
                nodeResponse = ex.ToString();
            }
            return(nodeResponse);
        }
		private string DownloadImage (string url)
		{
			try {
			    using (var stream = new MemoryStream ()) {
					using (var imageUrl = new Java.Net.URL (url)) {
						var options = new BitmapFactory.Options {
							InSampleSize = 1,
							InPurgeable = true
						};

						var bit = BitmapFactory.DecodeStream (imageUrl.OpenStream (), null, options);
						bit.Compress (Bitmap.CompressFormat.Png, 70, stream);
					}
					var imageBytes = stream.ToArray ();

					File.WriteAllBytes (this.Path, imageBytes);
				}
			} catch (Exception ex) {
				Log.WriteLine (LogPriority.Error, "GetImageFromBitmap Error", ex.Message);
			}

			return this.Path;
		}
        private string DownloadImage(string url)
        {
            try {
                using (var stream = new MemoryStream()) {
                    using (var imageUrl = new Java.Net.URL(url)) {
                        var options = new BitmapFactory.Options {
                            InSampleSize = 1,
                            InPurgeable  = true
                        };

                        var bit = BitmapFactory.DecodeStream(imageUrl.OpenStream(), null, options);
                        bit.Compress(Bitmap.CompressFormat.Png, 70, stream);
                    }
                    var imageBytes = stream.ToArray();

                    File.WriteAllBytes(this.Path, imageBytes);
                }
            } catch (Exception ex) {
                Log.WriteLine(LogPriority.Error, "GetImageFromBitmap Error", ex.Message);
            }

            return(this.Path);
        }
Exemple #25
0
        protected async override void OnStart()
        {
            base.OnStart();

            await _nickViewModel.GetLocation();
            await _nickViewModel.GetItem();
            _nickViewModel.GetStrings();

            string nick = _nickViewModel.PickedNick.Name;
            string location = _nickViewModel.Location.Name;
            string item = _nickViewModel.Item.Name;

            _greetingsText.Text = _nickViewModel.GreetingString;
            _resultText.Text = _nickViewModel.ResultString;

            string ImageName = System.IO.Path.GetFileNameWithoutExtension(_nickViewModel.PickedNick.ImageName);
            int id = Resources.GetIdentifier(ImageName, "drawable", PackageName);
            _nicImage.SetImageResource(id);

            if (_nickViewModel.Location.Local)
            {
                ImageName = System.IO.Path.GetFileNameWithoutExtension(_nickViewModel.Location.ImageName);
                id = Resources.GetIdentifier(ImageName, "drawable", PackageName);
                _greetingsImage.SetImageResource(id);
            }
            else
            {
                try
                {
                    Java.Net.URL locationUrl = new Java.Net.URL(_nickViewModel.Location.ImageName);
                    Bitmap bitmap = BitmapFactory.DecodeStream(locationUrl.OpenConnection().InputStream);
                    _greetingsImage.SetImageBitmap(bitmap);
                }
                catch ( Exception exc)
                {
                    Console.WriteLine(exc.ToString());
                }
            }

            ImageName = System.IO.Path.GetFileNameWithoutExtension(_nickViewModel.Item.ImageName);
            id = Resources.GetIdentifier(ImageName, "drawable", PackageName);
            _itemImage.SetImageResource(id);
        }
Exemple #26
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url      = new Java.Net.URL(java_uri);

            var body = default(RequestBody);

            if (request.Content != null)
            {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                body = RequestBody.Create(MediaType.Parse(request.Content.Headers.ContentType.MediaType), bytes);
            }

            var builder = new Request.Builder()
                          .Method(request.Method.Method.ToUpperInvariant(), body)
                          .Url(url);

            var keyValuePairs = request.Headers
                                .Union(request.Content != null ?
                                       (IEnumerable <KeyValuePair <string, IEnumerable <string> > >)request.Content.Headers :
                                       Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >());

            foreach (var kvp in keyValuePairs)
            {
                builder.AddHeader(kvp.Key, String.Join(",", kvp.Value));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var rq   = builder.Build();
            var call = client.NewCall(rq);

            cancellationToken.Register(() => call.Cancel());

            var resp = default(Response);

            try {
                resp = await call.EnqueueAsync().ConfigureAwait(false);
            } catch (IOException ex) {
                if (ex.Message.ToLowerInvariant().Contains("canceled"))
                {
                    throw new OperationCanceledException();
                }

                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());

            if (respBody != null)
            {
                var content = new ProgressStreamContent(respBody.ByteStream(), cancellationToken);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content      = content;
            }
            else
            {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();

            foreach (var k in respHeaders.Names())
            {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return(ret);
        }
		static bool Download(Uri uri, string target)
		{
			var buffer = new byte[4 * 1024];

			try
			{   // use Java.Net.URL instead of WebClient...
				var tmpfile = target + ".tmp";
				var imageUrl = new Java.Net.URL(uri.AbsoluteUri);
				var stream = imageUrl.OpenStream();
				LogDebug("====== open " + ImageName(uri.AbsoluteUri));
				using (var o = File.Open(tmpfile, FileMode.OpenOrCreate)) {
					byte[] buf = new byte[1024];
					int r;
					while ((r = stream.Read(buf, 0, buf.Length)) > 0) {
						o.Write(buf, 0, r);
					}
				}

				//using (var file = new FileStream(tmpfile, FileMode.Create, FileAccess.Write, FileShare.Read))
				//{
				//var req = WebRequest.Create(uri) as HttpWebRequest;

				//using (var resp = req.GetResponse())
				//{
				//    using (var s = resp.GetResponseStream())
				//    {
				//        int n;
				//        while ((n = s.Read(buffer, 0, buffer.Length)) > 0)
				//        {
				//            file.Write(buffer, 0, n);
				//        }
				//    }
				//}
				//}
				if (!File.Exists(target))   // we're never updating images if they change, to reduce Exceptions and speed up
					File.Move(tmpfile, target);
				return true;
			}
			catch (Exception e)
			{
				LogDebug(String.Format("Problem with {0} {1}", uri, e.Message));
				return false;
			}
		}
Exemple #28
0
        public static async Task <MovieDetails> GetMovieDetails(string movieID, string type)
        {
            string key = "253ceb1e198e26b094348524da5bc8ab";

            string query = string.Format("https://api.themoviedb.org/3/{0}/{1}?api_key={2}", type, movieID, key);

            var result = downloadjson.getJson(query);

            MovieDetails current = null;

            if (type == "movie")
            {
                //create new object
                current = new MovieDetails();
                try { current.title = result["original_title"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); };
                try { current.ID = (int)result["id"]; } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.imdbID = result["imdb_id"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.budget = (string)result["budget"]; } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.overview = result["overview"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.release_date = result["release_date"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.duration = (int)result["runtime"]; } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.revenue = (int)result["revenue"]; } catch (Exception ex) { Console.Write(ex.ToString()); }

                try
                {
                    Java.Net.URL link2 = new Java.Net.URL("http://image.tmdb.org/t/p/w185/" + result["poster_path"].ToString());
                    await Task.Run(() => { current.poster = BitmapFactory.DecodeStream(link2.OpenStream()); });
                }
                catch (Exception ex) { Console.Write(ex.ToString()); }
                //**************** SKATIOMA ZANRUS ***************************

                JArray   items  = (JArray)result["genres"];
                int      length = items.Count;
                string[] ar     = new string[length];
                for (int i = 0; i < length; i++)
                {
                    ar[i] = result["genres"][i]["name"].ToString();
                }
                current.genres = ar;

                try
                {
                    query = string.Format("http://api.themoviedb.org/3/movie/{0}/videos?api_key={1}", movieID, key);
                    var objectas = downloadjson.getJson(query);
                    current.trailer = objectas["results"][0]["key"].ToString();
                }
                catch (Exception ex) { Console.Write(ex.ToString()); }
            }
            else if (type == "tv")
            {
                current = new MovieDetails();
                try { current.title = result["name"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); };
                try { current.ID = (int)result["id"]; } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.imdbID = result["imdb_id"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.overview = result["overview"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); }
                try { current.first_air_date_date = result["first_air_date"].ToString(); } catch (Exception ex) { Console.Write(ex.ToString()); }
                current.duration = (int)result["episode_run_time"][0];
                try
                {
                    Java.Net.URL link2 = new Java.Net.URL("http://image.tmdb.org/t/p/w185/" + result["poster_path"].ToString());
                    await Task.Run(() => { current.poster = BitmapFactory.DecodeStream(link2.OpenStream()); });
                }
                catch (Exception ex) { Console.Write(ex.ToString()); }
                //**************** SKATIOMA ZANRUS ***************************

                JArray   items  = (JArray)result["genres"];
                int      length = items.Count;
                string[] ar     = new string[length];
                for (int i = 0; i < length; i++)
                {
                    ar[i] = result["genres"][i]["name"].ToString();
                }
                current.genres = ar;

                try
                {
                    query = string.Format("http://api.themoviedb.org/3/tv/{0}/videos?api_key={1}", movieID, key);
                    var objectas = downloadjson.getJson(query);
                    current.trailer = objectas["results"][0]["key"].ToString();
                }
                catch (Exception ex) { Console.Write(ex.ToString()); }

                current.created_by_name    = Lolas(result, "created_by", "name");
                current.seasons            = Lolas(result, "seasons", "id");
                current.networks_id        = Lolas(result, "networks", "name");
                current.status             = result["status"].ToString();
                current.number_of_seasons  = result["number_of_seasons"].ToString();
                current.number_of_episodes = result["number_of_episodes"].ToString();
                current.release_date       = result["first_air_date"].ToString();
            }


            return(current);
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var clientBuilder = Client.NewBuilder();

            // Support self-signed certificates
            if (EnableUntrustedCertificates)
            {
                // Install the all-trusting trust manager
                var trustManager = customTrustManager ?? new CustomX509TrustManager();

                var sslContext = SSLContext.GetInstance("SSL");
                sslContext.Init(null, new ITrustManager[] { trustManager }, new Java.Security.SecureRandom());

                // Create an ssl socket factory with our all-trusting manager
                var sslSocketFactory = sslContext.SocketFactory;

                clientBuilder.SslSocketFactory(sslSocketFactory, trustManager);
            }

            if (Timeout != null)
            {
                var timeout = (long)Timeout.Value.TotalMilliseconds;
                clientBuilder.ConnectTimeout(timeout, TimeUnit.Milliseconds);
                clientBuilder.WriteTimeout(timeout, TimeUnit.Milliseconds);
                clientBuilder.ReadTimeout(timeout, TimeUnit.Milliseconds);
            }

            Client = clientBuilder.Build();

            //RegisterForProgress(request, this.HandleProgress);

            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url      = new Java.Net.URL(java_uri);

            var body = default(RequestBody);

            if (request.Content != null)
            {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                var contentType = "text/plain";
                if (request.Content.Headers.ContentType != null)
                {
                    contentType = String.Join(" ", request.Content.Headers.GetValues("Content-Type"));
                }
                body = RequestBody.Create(MediaType.Parse(contentType), bytes);
            }

            var requestBuilder = new Request.Builder()
                                 .Method(request.Method.Method.ToUpperInvariant(), body)
                                 .Url(url);

            if (DisableCaching)
            {
                requestBuilder.CacheControl(noCacheCacheControl);
            }

            var keyValuePairs = request.Headers
                                .Union(request.Content != null ?
                                       (IEnumerable <KeyValuePair <string, IEnumerable <string> > >)request.Content.Headers :
                                       Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >());

            // Add Cookie Header if there's any cookie for the domain in the cookie jar
            var stringBuilder = new StringBuilder();

            if (Client.CookieJar() != null)
            {
                var jar     = Client.CookieJar();
                var cookies = jar.LoadForRequest(HttpUrl.Get(url));
                foreach (var cookie in cookies)
                {
                    stringBuilder.Append(cookie.Name() + "=" + cookie.Value() + ";");
                }
            }

            foreach (var kvp in keyValuePairs)
            {
                if (kvp.Key == "Cookie")
                {
                    foreach (var val in kvp.Value)
                    {
                        stringBuilder.Append(val + ";");
                    }
                }
                else
                {
                    requestBuilder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value));
                }
            }

            if (stringBuilder.Length > 0)
            {
                requestBuilder.AddHeader("Cookie", stringBuilder.ToString().TrimEnd(';'));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var rq   = requestBuilder.Build();
            var call = Client.NewCall(rq);

            // NB: Even closing a socket must be done off the UI thread. Cray!
            cancellationToken.Register(() => Task.Run(() => call.Cancel()));

            var resp = default(Response);

            try
            {
                resp = await call.EnqueueAsync().ConfigureAwait(false);

                var newReq = resp.Request();
                var newUri = newReq == null ? null : newReq.Url().Uri();
                request.RequestUri = new Uri(newUri.ToString());
                if (throwOnCaptiveNetwork && newUri != null)
                {
                    if (url.Host != newUri.Host)
                    {
                        throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString()));
                    }
                }
            }
            catch (IOException ex)
            {
                if (ex.Message.ToLowerInvariant().Contains("canceled"))
                {
                    throw new System.OperationCanceledException();
                }

                // Calling HttpClient methods should throw .Net Exception when fail #5
                throw new HttpRequestException(ex.Message, ex);
            }

            /*catch (Java.Lang.LinkageError ex)
             * {
             *  throw new HttpRequestException(ex.Message, ex);
             * }*/

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());

            ret.RequestMessage = request;
            ret.ReasonPhrase   = resp.Message();

            // ReasonPhrase is empty under HTTPS #8
            if (string.IsNullOrEmpty(ret.ReasonPhrase))
            {
                try
                {
                    ret.ReasonPhrase = ((ReasonPhrases)resp.Code()).ToString().Replace('_', ' ');
                }
#pragma warning disable 0168
                catch (Exception ex)
                {
                    ret.ReasonPhrase = "Unassigned";
                }
#pragma warning restore 0168
            }

            if (respBody != null)
            {
                var content = new ProgressStreamContent(request.RequestUri.AbsoluteUri, respBody.ByteStream(), CancellationToken.None);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content      = content;
            }
            else
            {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();
            foreach (var k in respHeaders.Names())
            {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return(ret);
        }
Exemple #30
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url      = new Java.Net.URL(java_uri);

            var body = default(RequestBody);

            if (request.Content != null)
            {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                var contentType = "text/plain";
                if (request.Content.Headers.ContentType != null)
                {
                    contentType = string.Join(" ", request.Content.Headers.GetValues("Content-Type"));
                }
                body = RequestBody.Create(bytes, MediaType.Parse(contentType));
            }

            var requestBuilder = new Request.Builder()
                                 .Method(request.Method.Method.ToUpperInvariant(), body)
                                 .Url(url);

            requestBuilder.CacheControl(_noCacheCacheControl);

            foreach (var kvp in request.Headers)
            {
                requestBuilder.AddHeader(kvp.Key, String.Join(",", kvp.Value));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var rq   = requestBuilder.Build();
            var call = _client.NewCall(rq);

            // NB: Even closing a socket must be done off the UI thread. Cray!
            cancellationToken.Register(() => Task.Run(() => call.Cancel()));

            var resp = default(Response);

            try
            {
                resp = await call.EnqueueAsync().ConfigureAwait(false);

                // 重定向
                //var newReq = resp.Request();
                //var newUri = newReq == null ? null : newReq.Url().Uri();
                //request.RequestUri = new Uri(newUri.ToString());
                //if (throwOnCaptiveNetwork && newUri != null)
                //{
                //    if (url.Host != newUri.Host)
                //    {
                //        throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString()));
                //    }
                //}
            }
            catch (IOException ex)
            {
                if (ex.Message.ToLowerInvariant().Contains("canceled"))
                {
                    throw new System.OperationCanceledException();
                }

                // Calling HttpClient methods should throw .Net Exception when fail #5
                throw new HttpRequestException(ex.Message, ex);
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());

            ret.RequestMessage = request;
            ret.ReasonPhrase   = resp.Message();

            // ReasonPhrase is empty under HTTPS #8
            if (string.IsNullOrEmpty(ret.ReasonPhrase))
            {
                try
                {
                    ret.ReasonPhrase = ((ReasonPhrases)resp.Code()).ToString().Replace('_', ' ');
                }
#pragma warning disable 0168
                catch (Exception ex)
                {
                    ret.ReasonPhrase = "Unassigned";
                }
#pragma warning restore 0168
            }

            if (respBody != null)
            {
                var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None);
                content.Progress = GetAndRemoveCallbackFromRegister(request);
                ret.Content      = content;
            }
            else
            {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            // 响应头
            var respHeaders = resp.Headers();
            foreach (var k in respHeaders.Names())
            {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return(ret);
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url = new Java.Net.URL(java_uri);

            var body = default(RequestBody);
            if (request.Content != null) {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                var contentType = "text/plain";
                if (request.Content.Headers.ContentType != null) {
                    contentType = String.Join(" ", request.Content.Headers.GetValues("Content-Type"));
                }
                body = RequestBody.Create(MediaType.Parse(contentType), bytes);
            }

            var builder = new Request.Builder()
                .Method(request.Method.Method.ToUpperInvariant(), body)
                .Url(url);

            if (DisableCaching) {
                builder.CacheControl(noCacheCacheControl);
            }

            var keyValuePairs = request.Headers
                .Union(request.Content != null ?
                    (IEnumerable<KeyValuePair<string, IEnumerable<string>>>)request.Content.Headers :
                    Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>());

            foreach (var kvp in keyValuePairs) builder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value));

            cancellationToken.ThrowIfCancellationRequested();

            var rq = builder.Build();
            var call = client.NewCall(rq);

            // NB: Even closing a socket must be done off the UI thread. Cray!
            cancellationToken.Register(() => Task.Run(() => call.Cancel()));

            var resp = default(Response);
            try {
                resp = await call.EnqueueAsync().ConfigureAwait(false);
                var newReq = resp.Request();
                var newUri = newReq == null ? null : newReq.Uri();
                request.RequestUri = new Uri(newUri.ToString());
                if (throwOnCaptiveNetwork && newUri != null) {
                    if (url.Host != newUri.Host) {
                        throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString()));
                    }
                }
            } catch (IOException ex) {
                if (ex.Message.ToLowerInvariant().Contains("canceled")) {
                    throw new OperationCanceledException();
                }

                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());
            ret.RequestMessage = request;
            ret.ReasonPhrase = resp.Message();
            if (respBody != null) {
                var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content = content;
            } else {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();
            foreach (var k in respHeaders.Names()) {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return ret;
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (_client == null)
            {
                _client = _builder.Build();
            }

            var javaUri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url     = new Java.Net.URL(javaUri);

            var body = default(RequestBody);

            if (request.Content != null)
            {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                var contentType = "text/plain";
                if (request.Content.Headers.ContentType != null)
                {
                    contentType = string.Join(" ", request.Content.Headers.GetValues("Content-Type"));
                }

                body = RequestBody.Create(MediaType.Parse(contentType), bytes);
            }

            var builder = new Request.Builder()
                          .Method(request.Method.Method.ToUpperInvariant(), body)
                          .Url(url);

            var keyValuePairs = request.Headers
                                .Union(request.Content != null ?
                                       request.Content.Headers :
                                       Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >());

            foreach (var kvp in keyValuePairs)
            {
                var headerSeparator = kvp.Key == "User-Agent" ? " " : ",";
                builder.AddHeader(kvp.Key, string.Join(headerSeparator, kvp.Value));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var rq   = builder.Build();
            var call = _client.NewCall(rq);

            // NB: Even closing a socket must be done off the UI thread. Cray!
            cancellationToken.Register(() => Task.Run(() => call.Cancel()));

            Response resp;

            try
            {
                resp = await call.ExecuteAsync().ConfigureAwait(false);
            }
            catch (IOException ex)
            {
                if (ex.Message != null && ex.Message.StartsWith("Certificate pinning failure!"))
                {
                    throw new WebException(ex.Message, WebExceptionStatus.TrustFailure);
                }
                if (ex.Message != null && ex.Message.ToLowerInvariant().Contains("canceled"))
                {
                    throw new System.OperationCanceledException();
                }
                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code())
            {
                RequestMessage = request,
                ReasonPhrase   = resp.Message()
            };

            if (respBody != null)
            {
                ret.Content = new StreamContent(respBody.ByteStream());
            }
            else
            {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();

            foreach (var k in respHeaders.Names())
            {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return(ret);
        }
Exemple #33
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url      = new Java.Net.URL(java_uri);

            var body = default(RequestBody);

            if (request.Content != null)
            {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                var contentType = "text/plain";
                if (request.Content.Headers.ContentType != null)
                {
                    contentType = String.Join(" ", request.Content.Headers.GetValues("Content-Type"));
                }
                body = RequestBody.Create(MediaType.Parse(contentType), bytes);
            }

            var builder = new Request.Builder()
                          .Method(request.Method.Method.ToUpperInvariant(), body)
                          .Url(url);

            if (DisableCaching)
            {
                builder.CacheControl(noCacheCacheControl);
            }

            var keyValuePairs = request.Headers
                                .Union(request.Content != null ?
                                       (IEnumerable <KeyValuePair <string, IEnumerable <string> > >)request.Content.Headers :
                                       Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >());

            foreach (var kvp in keyValuePairs)
            {
                builder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var rq   = builder.Build();
            var call = client.NewCall(rq);

            // NB: Even closing a socket must be done off the UI thread. Cray!
            cancellationToken.Register(() => Task.Run(() => call.Cancel()));

            var resp = default(Response);

            try {
                resp = await call.EnqueueAsync().ConfigureAwait(false);

                var newReq = resp.Request();
                var newUri = newReq == null ? null : newReq.Uri();
                request.RequestUri = new Uri(newUri.ToString());
                if (throwOnCaptiveNetwork && newUri != null)
                {
                    if (url.Host != newUri.Host)
                    {
                        throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString()));
                    }
                }
            } catch (IOException ex) {
                if (ex.Message.ToLowerInvariant().Contains("canceled"))
                {
                    throw new OperationCanceledException();
                }

                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());

            ret.RequestMessage = request;
            ret.ReasonPhrase   = resp.Message();
            if (respBody != null)
            {
                var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content      = content;
            }
            else
            {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();

            foreach (var k in respHeaders.Names())
            {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return(ret);
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url      = new Java.Net.URL(java_uri);

            Java.Net.HttpURLConnection rq;
            try {
                rq = client.Open(url);
            } catch (Java.Net.UnknownHostException e) {
                throw new WebException("Name resolution failure", e, WebExceptionStatus.NameResolutionFailure, null);
            }
            rq.RequestMethod = request.Method.Method.ToUpperInvariant();

            foreach (var kvp in request.Headers)
            {
                rq.SetRequestProperty(kvp.Key, kvp.Value.FirstOrDefault());
            }

            if (request.Content != null)
            {
                foreach (var kvp in request.Content.Headers)
                {
                    rq.SetRequestProperty(kvp.Key, kvp.Value.FirstOrDefault());
                }

                await Task.Run(async() => {
                    var contentStream = await request.Content.ReadAsStreamAsync().ConfigureAwait(false);
                    await copyToAsync(contentStream, rq.OutputStream, cancellationToken).ConfigureAwait(false);
                }, cancellationToken).ConfigureAwait(false);

                rq.OutputStream.Close();
            }

            return(await Task.Run(() => {
                // NB: This is the line that blocks until we have headers
                var ret = new HttpResponseMessage((HttpStatusCode)rq.ResponseCode);

                // Test to see if we're being redirected (i.e. in a captive network)
                if (throwOnCaptiveNetwork && (url.Host != rq.URL.Host))
                {
                    throw new WebException("Hostnames don't match, you are probably on a captive network");
                }

                cancellationToken.ThrowIfCancellationRequested();

                ret.Content = new StreamContent(new ConcatenatingStream(new Func <Stream>[] {
                    () => ret.IsSuccessStatusCode ? rq.InputStream : new MemoryStream(),
                    () => rq.ErrorStream ?? new MemoryStream(),
                }, true));

                var keyValuePairs = rq.HeaderFields.Keys
                                    .Where(k => k != null) // Yes, this happens. I can't even.
                                    .SelectMany(k => rq.HeaderFields[k]
                                                .Select(val => new { Key = k, Value = val }));

                foreach (var v in keyValuePairs)
                {
                    ret.Headers.TryAddWithoutValidation(v.Key, v.Value);
                    ret.Content.Headers.TryAddWithoutValidation(v.Key, v.Value);
                }

                cancellationToken.Register(ret.Content.Dispose);

                ret.RequestMessage = request;
                return ret;
            }, cancellationToken).ConfigureAwait(false));
        }