protected JsonObject ParseURL(string urlstring)
        {
            Log.Debug(TAG, "Parse URL: " + urlstring);
            InputStream inputStream = null;

            mPrefixUrl = mContext.Resources.GetString(Resource.String.prefix_url);

            try {
                Java.Net.URL url           = new Java.Net.URL(urlstring);
                var          urlConnection = url.OpenConnection();
                inputStream = new BufferedInputStream(urlConnection.InputStream);
                var reader = new BufferedReader(new InputStreamReader(
                                                    urlConnection.InputStream, "iso-8859-1"), 8);
                var    sb   = new StringBuilder();
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    sb.Append(line);
                }
                var json = sb.ToString();
                return((JsonObject)JsonObject.Parse(json));
            } catch (Exception e) {
                Log.Debug(TAG, "Failed to parse the json for media list", e);
                return(null);
            } finally {
                if (null != inputStream)
                {
                    try {
                        inputStream.Close();
                    } catch (IOException e) {
                        Log.Debug(TAG, "Json feed closed", e);
                    }
                }
            }
        }
Пример #2
0
        protected MovieJson[] ParseURL(string urlstring)
        {
            Log.Debug(TAG, "Parse URL: " + urlstring);
            InputStream inputStream = null;

            try {
                Java.Net.URL url           = new Java.Net.URL(urlstring);
                var          urlConnection = url.OpenConnection();
                inputStream = new BufferedInputStream(urlConnection.InputStream);
                var reader = new BufferedReader(new InputStreamReader(
                                                    urlConnection.InputStream, "iso-8859-1"), 8);
                var    sb   = new StringBuilder();
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    sb.Append(line);
                }
                var json     = sb.ToString();
                var response = JsonConvert.DeserializeObject <MoviesResponse> (json);
                return(response.Results);
            } catch (Exception e) {
                Log.Debug(TAG, "Failed to parse the json for media list", e);
                return(null);
            } finally {
                if (null != inputStream)
                {
                    try {
                        inputStream.Close();
                    } catch (IOException e) {
                        Log.Debug(TAG, "Json feed closed", e);
                    }
                }
            }
        }
        private static string GetUpcomingFixturesForTeam(int teamId, bool forceRefresh = false)
        {
            var url = new URL(string.Format("http://www.football-data.org/team/{0}/fixtures/upcoming?venue=home", teamId));
            var urlConnection = (HttpURLConnection)url.OpenConnection();
            try
            {
                if (forceRefresh)
                {
                    urlConnection.AddRequestProperty("Cache-Control", "no-cache");
                }
                else
                {
                    urlConnection.AddRequestProperty("Cache-Control", "max-stale=" + 86400); //1 day
                }

                urlConnection.SetUseCaches(true);
                var reader = new BufferedReader(new InputStreamReader(urlConnection.GetInputStream()));
                var builder = new StringBuilder();
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    builder.Append(line);
                }
                return builder.ToString();
            }
            catch (Exception ex)
            {
                Log.I(Constants.Tag, "Error getting fixtures. " + ex.Message + " " + ex.StackTrace);
                return null;
            }
        }
Пример #4
0
 public Bitmap getBitmap(string path)
 {
     try
     {
         Java.Net.URL url = new Java.Net.URL(path);
         Java.Net.HttpURLConnection conn = (Java.Net.HttpURLConnection)url.OpenConnection();
         conn.ConnectTimeout = 3000;
         conn.RequestMethod  = "GET";
         if (conn.ResponseCode == Java.Net.HttpStatus.Ok)
         {
             Bitmap bitmap = BitmapFactory.DecodeStream(conn.InputStream);
             return(bitmap);
         }
         else
         {
             var re = conn.ResponseCode;
             //算求来
         }
     }
     catch (Exception ex)
     {
         //LogManager.WriteSpeechErrorLog("getBitmap:Error" + ex.Message);
         Toast.MakeText(this, ex.Message, ToastLength.Long);
     }
     return(null);
 }
Пример #5
0
 /// <summary>
 /// TODO:这个方法 总是会报异常 原因不明确 ErrorException of type 'Java.Lang.RuntimeException' was thrown.
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public Bitmap getBitmap(string path)
 {
     try
     {
         Java.Net.URL url = new Java.Net.URL(path);
         LogManager.WriteSystemLog("Java.Net.URL url = new Java.Net.URL(path)");
         Java.Net.HttpURLConnection conn = (Java.Net.HttpURLConnection)url.OpenConnection();
         LogManager.WriteSystemLog("Java.Net.HttpURLConnection conn = (Java.Net.HttpURLConnection)url.OpenConnection();");
         conn.ConnectTimeout = 4000;
         conn.RequestMethod  = "GET";
         LogManager.WriteSystemLog(" conn.RequestMethod = GET;");
         if (conn.ResponseCode == Java.Net.HttpStatus.Ok)
         {
             LogManager.WriteSystemLog("status ok");
             Bitmap bitmap = BitmapFactory.DecodeStream(conn.InputStream);
             LogManager.WriteSystemLog(" conn.RequestMethod = GET;");
             return(bitmap);
         }
         else
         {
             var re = conn.ResponseCode;
             LogManager.WriteSystemLog("status not ok");
             // LogManager.WriteSystemLog("ReCode:" + re.ToString());
         }
     }
     catch (Exception ex)
     {
         // LogManager.WriteSystemLog("getBitmap:Error" + ex.stat);
     }
     return(null);
 }
Пример #6
0
        private string DownloadFile(string sUrl, string filePath)
        {
            try
            {
                //get result from uri
                URL           url        = new Java.Net.URL(sUrl);
                URLConnection connection = url.OpenConnection();
                connection.Connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lengthOfFile = connection.ContentLength;

                // download the file
                InputStream input = new BufferedInputStream(url.OpenStream(), 8192);

                // Output stream
                Log.WriteLine(LogPriority.Info, "DownloadFile FilePath ", filePath);
                OutputStream output = new FileOutputStream(filePath);

                byte[] data = new byte[1024];

                long total = 0;

                int count;
                while ((count = input.Read(data)) != -1)
                {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    //publishProgress("" + (int)((total * 100) / lengthOfFile));
                    if (total % 10 == 10)                     //log for every 10th increment
                    {
                        Log.WriteLine(LogPriority.Info, "DownloadFile Progress ", "" + (int)((total * 100) / lengthOfFile));
                    }

                    // writing data to file
                    output.Write(data, 0, count);
                }

                // flushing output
                output.Flush();

                // closing streams
                output.Close();
                input.Close();
            }
            catch (Exception ex)
            {
                Log.WriteLine(LogPriority.Error, "DownloadFile Error", ex.Message);
            }
            return(filePath);
        }
Пример #7
0
 public void DownloadImage(string urlString)
 {
     try
     {
         var url = new URL(urlString);
         var stream = url.OpenConnection().InputStream;
         var image = BitmapFactory.DecodeStream(stream);
         ImageDownloadCompleted?.Invoke(image);
     }
     catch (Exception e)
     {
         Log.Debug("Exception", "Image failed to download: " + e.ToString());
     }
 }
Пример #8
0
        /// <summary>
        /// Command is sent (parameters are in path), and the result will be in commandResult
        /// </summary>
        /// <param name="path"></param>
        /// <param name="commandResult"></param>
        protected void SendGetCommand(string path, CommandResult commandResult)
        {
#if WINDOWS
            new Thread(() =>
            {
                HttpClient client            = new HttpClient();
                HttpResponseMessage response = client.GetAsync(URL + path).Result;

                if (response.IsSuccessStatusCode)
                {
                    commandResult(response.Content.ReadAsStringAsync().Result);
                }
                else
                {
                    //HIBA
                    //commandResult(null);
                }
            }).Start();
#endif
#if ANDROID
            new System.Threading.Thread(() =>
            {
                Java.Net.URL obj      = new Java.Net.URL(URL + path);
                HttpURLConnection con = (HttpURLConnection)obj.OpenConnection();
                con.RequestMethod     = "GET";

                HttpStatus responseCode = con.ResponseCode;

                BufferedReader br = new BufferedReader(new InputStreamReader(con.InputStream));
                System.String inputLine;
                System.String response = "";

                inputLine = br.ReadLine();
                while (inputLine != null)
                {
                    response += inputLine;
                    inputLine = br.ReadLine();
                }
                br.Close();

                commandResult(response);
            }).Start();
#endif
        }
Пример #9
0
        // gets a file given a url
        // puts in path
        public override async Task <bool> InstallRemoteFile(string link, string path)
        {
            if (context == null)
            {
                throw new AppServiceNotInitializedException("You must call Init() before using the AppService");
            }
            else
            {
                return(await Task.Run(() =>
                {
                    // path will just be a filename


                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }

                    var url = new Java.Net.URL(link);
                    var connection = (HttpURLConnection)url.OpenConnection();
                    connection.RequestMethod = "GET";
                    connection.DoOutput = true;
                    connection.Connect();

                    using var input = url.OpenStream();
                    using var fos = new FileOutputStream(path);

                    var buffer = new byte[1024];
                    int length = 0;
                    while ((length = input.Read(buffer, 0, 1024)) > 0)
                    {
                        fos.Write(buffer, 0, length);
                    }
                    fos.Close();
                    input.Close();

                    return Install(path);
                }));
            }
        }
Пример #10
0
		public Bitmap GetBitmap(string url) 
		{
			Java.IO.File file=fileCache.GetFile(url);
			//先从文件缓存中查找是否有
			//from SD cache
			Bitmap b = DecodeFile(file);
			if(b!=null)
				return b;
			/**
         *  最后从指定的url中下载图片
         */
			//from web
			try {
				Bitmap bitmap=null;
				URL imageUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection)imageUrl.OpenConnection();
				conn.Connect();
				conn.ConnectTimeout=30000;
				conn.ReadTimeout=30000;
				conn.InstanceFollowRedirects=true;
				var inStream=conn.InputStream;
				var outputStream = new FileOutputStream(file);
				CopyStream(inStream, outputStream);
				outputStream.Close();
				conn.Disconnect();
				bitmap = DecodeFile(file);

				return bitmap;

			} catch (Throwable ex){
				
				ex.PrintStackTrace();
				if(ex is OutOfMemoryError)
					memoryCache.Clear();
				return null;
			}

		}
        private Bitmap GetBitmap(string url)
        {
            File f= m_FileCache.GetFile(url);

            ////from SD cache
            Bitmap b = DecodeFile(f, m_Scale);
            if(b!=null)
                return b;

            ////from web
            try
            {
                Bitmap bitmap=null;
                URL imageUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection)imageUrl.OpenConnection();
                conn.ConnectTimeout = 5000;
                conn.ReadTimeout = 5000;
                conn.InstanceFollowRedirects = true;

                if (conn.ErrorStream != null)
                    return null;

                var inputStream = conn.InputStream;
                OutputStream os = new FileOutputStream(f);
                CopyStream(inputStream, os);
                os.Close();
                bitmap = DecodeFile(f, m_Scale);
                return bitmap;
            }
            catch (Exception ex)
            {
               //ex.printStackTrace();
               return null;
            }
        }
Пример #12
0
        /// <summary>
        /// Command is sent (parameters are in path), the body is the parameter Object, what will be serialized via json
        /// Result will be in commandResult.
        /// PUT method
        /// </summary>
        /// <param name="path"></param>
        /// <param name="parameter"></param>
        /// <param name="commandResult"></param>
        protected void SendPutCommand(string path, System.Object parameter, CommandResult commandResult)
        {
#if WINDOWS
            new Thread(() =>
            {
                HttpClient client            = new HttpClient();
                HttpContent content          = new StringContent(fastJSON.JSON.ToJSON(parameter), Encoding.UTF8, "application/json");
                HttpResponseMessage response = client.PutAsync(URL + path, content).Result;

                if (response.IsSuccessStatusCode)
                {
                    commandResult(response.Content.ReadAsStringAsync().Result);
                }
                else
                {
                    //HIBA
                    //commandResult(null);
                }
            }).Start();
#endif
#if ANDROID
            new System.Threading.Thread(() =>
            {
                Java.Net.URL obj      = new Java.Net.URL(URL + path);
                HttpURLConnection con = (HttpURLConnection)obj.OpenConnection();
                con.RequestMethod     = "PUT";

                OutputStreamWriter outstream = new OutputStreamWriter(con.OutputStream);

                outstream.Write(fastJSON.JSON.ToJSON(parameter));
                outstream.Close();

                HttpStatus responseCode = con.ResponseCode;

                BufferedReader br = new BufferedReader(new InputStreamReader(con.InputStream));

                /*System.String inputLine;
                 *      System.String response = "";
                 *
                 * inputLine = br.ReadLine();
                 *      while (inputLine != null) {
                 *  response += inputLine;
                 *  inputLine = br.ReadLine();
                 *      }*/
                br.Close();

                commandResult(null);


                /*HttpClient client = new HttpClient();
                 * HttpResponseMessage response = client.GetAsync(URL + path).Result;
                 *
                 * if (response.IsSuccessStatusCode)
                 * {
                 *  commandResult(response.Content.ReadAsStringAsync().Result);
                 * }
                 * else
                 * {
                 *  //HIBA
                 *  //commandResult(null);
                 * }*/
            }).Start();
#endif
        }
Пример #13
0
		/** Called when the activity is first created. */
		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);

			if (APP_ID == null) {
				Util.ShowAlert (this, "Warning", "Facebook Applicaton ID must be " +
					"specified before running this example: see Example.java");
			}

			SetContentView (Resource.Layout.main);
			mLoginButton = (LoginButton)FindViewById (Resource.Id.login);
			mText = (TextView)FindViewById (Resource.Id.txt);
			mRequestButton = (Button)FindViewById (Resource.Id.requestButton);
			mPostButton = (Button)FindViewById (Resource.Id.postButton);
			mDeleteButton = (Button)FindViewById (Resource.Id.deletePostButton);
			mUploadButton = (Button)FindViewById (Resource.Id.uploadButton);

			mFacebook = new Facebook (APP_ID);
			mAsyncRunner = new AsyncFacebookRunner (mFacebook);

			SessionStore.Restore (mFacebook, this);
			SessionEvents.AddAuthListener (new SampleAuthListener (this));
			SessionEvents.AddLogoutListener (new SampleLogoutListener (this));
			mLoginButton.Init (this, mFacebook);

			mRequestButton.Click += delegate {
				mAsyncRunner.Request ("me", new SampleRequestListener (this));
			};
			mRequestButton.Visibility = mFacebook.IsSessionValid ?
                ViewStates.Visible :
                ViewStates.Invisible;

			mUploadButton.Click += async delegate {
				Bundle parameters = new Bundle ();
				parameters.PutString ("method", "photos.upload");

				URL uploadFileUrl = null;
				try {
					uploadFileUrl = new URL (
						"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
				} catch (MalformedURLException e) {
					e.PrintStackTrace ();
				}
				try {
					HttpURLConnection conn = (HttpURLConnection)uploadFileUrl.OpenConnection ();
					conn.DoInput = true;
					await conn.ConnectAsync ();
					int length = conn.ContentLength;

					byte[] imgData = new byte[length];
					var ins = conn.InputStream;
					await ins.ReadAsync (imgData, 0, imgData.Length);
					parameters.PutByteArray ("picture", imgData);

				} catch (IOException e) {
					e.PrintStackTrace ();
				}

				mAsyncRunner.Request (null, parameters, "POST",
				                      new SampleUploadListener (this), null);
			};
			mUploadButton.Visibility = mFacebook.IsSessionValid ?
                ViewStates.Visible :
                ViewStates.Invisible;

			mPostButton.Click += delegate {
				mFacebook.Dialog (this, "feed",
				                  new SampleDialogListener (this));
			};
			mPostButton.Visibility = mFacebook.IsSessionValid ?
                ViewStates.Visible :
                ViewStates.Invisible;
		}
Пример #14
0
		//***************************************************************************************************
		//******************FUNCION  QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO***********************
		//***************************************************************************************************
		void DescargaArchivo(ProgressCircleView  tem_pcv, string url_archivo)
		{
			//OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS 
			//EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR
			string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ;
			Java.IO.File directory = new Java.IO.File (filePath);

			//VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS
			if(directory.Exists() ==false)
			{
				directory.Mkdir();
			}

			//ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR
			URL url = new URL(url_archivo);

			//CABRIMOS UNA CONEXION CON EL ARCHIVO
			URLConnection conexion = url.OpenConnection();
			conexion.Connect ();

			//OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR
			int lenghtOfFile = conexion.ContentLength;

			//CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION
			InputStream input = new BufferedInputStream(url.OpenStream());

			//ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO
			//PARA ESTE CASO CONSERVA EL MISMO NOMBRE
			string NewFile = directory.AbsolutePath+ "/"+ url_archivo.Substring (url_archivo.LastIndexOf ("/") + 1);

			//CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO
			OutputStream output = new FileOutputStream(NewFile);
			byte[] data= new byte[lenghtOfFile];
			long total = 0;

			int count;
			//COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM
			while ((count = input.Read(data)) != -1) 
			{
				total += count;
				//CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL
				//QUE SE ENCUENTRA EN EL HILO PRINCIPAL
				RunOnUiThread(() => tem_pcv.setPorcentaje ((int)((total*100)/lenghtOfFile)));

				//ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM
				output.Write(data, 0, count);

			}
			output.Flush();
			output.Close();
			input.Close();

			//INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100%
			RunOnUiThread(() => tem_pcv.setPorcentaje (100));

		}
Пример #15
0
			protected override Java.Lang.Object DoInBackground (params Java.Lang.Object[] @params)
			{
				//REALIZAMOS EL PROCESO DE DESCARGA DEL ARCHIVO
				try{

					string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ;
					Java.IO.File directory = new Java.IO.File (filePath);
					if(directory.Exists() ==false)
					{
						directory.Mkdir();
					}

					//RECUPERAMOS LA DIRECCION DEL ARCHIVO QUE DESEAMOS DESCARGAR
					string url_link = @params [0].ToString ();
					URL url = new URL(url_link);
					URLConnection conexion = url.OpenConnection();
					conexion.Connect ();

					int lenghtOfFile = conexion.ContentLength;
					InputStream input = new BufferedInputStream(url.OpenStream());

					string NewImageFile = directory.AbsolutePath+ "/"+ url_link.Substring (url_link.LastIndexOf ("/") + 1);
					OutputStream output = new FileOutputStream(NewImageFile);
					byte[] data= new byte[lenghtOfFile];


					int count;
					while ((count = input.Read(data)) != -1) 
					{
						output.Write(data, 0, count);
					}
					output.Flush();
					output.Close();
					input.Close();
					return true;

				}catch {
					return  false;
				}

			}
Пример #16
0
 private Bitmap LoadImage(string imageUrl)
 {
     var url= new URL (imageUrl);
         var imageBitmap = BitmapFactory.DecodeStream (url.OpenConnection ().InputStream);
         return imageBitmap;
 }
Пример #17
0
        private Bitmap LoadBitmap(string source)
        {
            try
            {
                if (m_control.UseCache)
                {
                    lock ( s_lock )
                    {
                        int urlHash = source.GetHashCode();

                        string path     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                        string filePath = System.IO.Path.Combine(path, string.Format("{0}.img", urlHash));
                        if (System.IO.File.Exists(filePath))
                        {
                            var fileAge = DateTime.UtcNow - System.IO.File.GetCreationTimeUtc(filePath);

                            if (fileAge < m_control.CacheTTL)
                            {
                                using (var fs = System.IO.File.OpenRead(filePath))
                                {
                                    var bitmap = BitmapFactory.DecodeStream(fs);
                                    return(bitmap);
                                }
                            }
                        }


                        using (var fs = System.IO.File.Create(filePath))
                        {
                            Java.Net.URL url = new Java.Net.URL(source);

                            using (URLConnection connection = url.OpenConnection())
                            {
                                using (var inputStream = connection.InputStream)
                                {
                                    inputStream.CopyTo(fs);
                                }
                            }


                            fs.Seek(0, SeekOrigin.Begin);

                            var bitmap = BitmapFactory.DecodeStream(fs);

                            return(bitmap);
                        }
                    }
                }
                else
                {
                    Java.Net.URL url = new Java.Net.URL(source);

                    var bitmap = BitmapFactory.DecodeStream(url.OpenConnection().InputStream);

                    return(bitmap);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Problem Loading Image {0} - {1}", source, ex);
                return(null);
            }
        }
            protected override string RunInBackground(params string[] @params)
            {
                for (int i = 0; i <= 2; i++)
                {
                    try
                    {
                        String sourceFileUri = MainActivity.rec_video_uri[i];

                        Java.Net.HttpURLConnection conn = null;
                        DataOutputStream           dos  = null;
                        String lineEnd = "\r\n";
                        String twoHyphens = "--";
                        String boundary = "*****";
                        int    bytesRead, bytesAvailable, bufferSize;
                        byte[] buffer;
                        int    maxBufferSize = 1 * 1024 * 1024;
                        File   sourceFile    = new File(sourceFileUri);

                        if (sourceFile.IsFile)
                        {
                            try
                            {
                                String upLoadServerUri = "http://140.114.28.134/VideoUpload/uploads/upload.php";

                                // Ppen a URL connection to the Server
                                FileInputStream fileInputStream = new FileInputStream(
                                    sourceFile);
                                Java.Net.URL url = new Java.Net.URL(upLoadServerUri);

                                // Open a HTTP connection to the URL
                                conn               = (Java.Net.HttpURLConnection)url.OpenConnection();
                                conn.DoInput       = true;  // Allow Inputs
                                conn.DoOutput      = true;  // Allow Outputs
                                conn.UseCaches     = false; // Don't use a Cached Copy
                                conn.RequestMethod = "POST";
                                conn.SetRequestProperty("Connection", "Keep-Alive");
                                conn.SetRequestProperty("ENCTYPE", "multipart/form-data");
                                conn.SetRequestProperty("Content-Type",
                                                        "multipart/form-data;boundary=" + boundary);
                                conn.SetRequestProperty("upload_name", sourceFileUri);

                                dos = new DataOutputStream(conn.OutputStream);

                                dos.WriteBytes(twoHyphens + boundary + lineEnd);
                                dos.WriteBytes("Content-Disposition: form-data; name=\"upload_name\";filename=\""
                                               + sourceFileUri + "\"" + lineEnd);

                                dos.WriteBytes(lineEnd);

                                // Create a buffer of maximum size
                                bytesAvailable = fileInputStream.Available();

                                bufferSize = Math.Min(bytesAvailable, maxBufferSize);
                                buffer     = new byte[bufferSize];

                                // Read file and write
                                bytesRead = fileInputStream.Read(buffer, 0, bufferSize);

                                while (bytesRead > 0)
                                {
                                    dos.Write(buffer, 0, bufferSize);
                                    bytesAvailable = fileInputStream.Available();
                                    bufferSize     = Math
                                                     .Min(bytesAvailable, maxBufferSize);
                                    bytesRead = fileInputStream.Read(buffer, 0,
                                                                     bufferSize);
                                }

                                // Send multipart form data necesssary after file
                                dos.WriteBytes(lineEnd);
                                dos.WriteBytes(twoHyphens + boundary + twoHyphens
                                               + lineEnd);

                                // Responses from the server (code and message)
                                serverResponseCode = conn.ResponseCode;
                                String serverResponseMessage = conn
                                                               .ResponseMessage;

                                // Close the streams
                                fileInputStream.Close();
                                dos.Flush();
                                dos.Close();
                            }
                            catch (Exception e)
                            {
                                System.Console.WriteLine(e.ToString());
                            }
                        } // End if-else block
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex.ToString());
                    }
                }
                progressDialog.Dismiss();

                return("Finished");
            }
Пример #19
0
 /// <summary>
 /// Open a connection and initialize it.
 /// </summary>
 private static URLConnection OpenConnection(URL url)
 {
     var connection = url.OpenConnection();
     var httpConnection = connection as HttpURLConnection;
     if (httpConnection != null)
     {
         httpConnection.InstanceFollowRedirects = true;
     }
     return connection;
 }
Пример #20
0
		/// <summary>
		/// 下载apk文件
		/// </summary>
		private void DownloadApk()
		{
			
			URL url = null;  
			Stream instream = null;  
			FileOutputStream outstream = null;  
			HttpURLConnection conn = null;  
			try
			{
				url = new URL(Global.AppPackagePath);
				//创建连接
				conn = (HttpURLConnection) url.OpenConnection();
				conn.Connect();

				conn.ConnectTimeout =20000;
				//获取文件大小
				var filelength = conn.ContentLength;
				instream = conn.InputStream;
				var file = new Java.IO.File(FILE_PATH);
				if(!file.Exists())
				{
					file.Mkdir();
				}
				outstream = new FileOutputStream(new Java.IO.File(saveFileName));

				int count =0;
				//缓存
				byte[] buff = new byte[1024];
				//写入文件中
				do
				{
					int numread = instream.Read(buff,0,buff.Length);
					count+=numread;
					//计算进度条位置
					progress = (int)(((float)count/filelength)*100);
				    //更新进度---- other question

					mProgressbar.Progress = progress;
					if(numread<=0)
					{
						//下载完成,安装新apk
						Task.Factory.StartNew(InStallApk);
						break;
					}
					//写入文件
					outstream.Write(buff,0,numread);

				}
				while(!cancelUpdate);//点击取消,停止下载
					
			}
			catch(Exception ex)
			{
				Android.Util.Log.Error (ex.StackTrace,ex.Message);
			}
			finally
			{
				if (instream != null)
					instream.Close ();
				if (outstream != null)
					outstream.Close ();
				if(conn!=null)
				    conn.Disconnect ();
			}
			dowloadDialog.Dismiss ();
		}
Пример #21
0
		protected JsonObject ParseURL (string urlstring)
		{
			Log.Debug (TAG, "Parse URL: " + urlstring);
			InputStream inputStream = null;

			mPrefixUrl = mContext.Resources.GetString (Resource.String.prefix_url);

			try {
				Java.Net.URL url = new Java.Net.URL (urlstring);
				var urlConnection = url.OpenConnection ();
				inputStream = new BufferedInputStream (urlConnection.InputStream);
				var reader = new BufferedReader (new InputStreamReader (
					             urlConnection.InputStream, "iso-8859-1"), 8);
				var sb = new StringBuilder ();
				string line = null;
				while ((line = reader.ReadLine ()) != null) {
					sb.Append (line);
				}
				var json = sb.ToString ();
				return (JsonObject)JsonObject.Parse (json);
			} catch (Exception e) {
				Log.Debug (TAG, "Failed to parse the json for media list", e);
				return null;
			} finally {
				if (null != inputStream) {
					try {
						inputStream.Close ();
					} catch (IOException e) {
						Log.Debug (TAG, "Json feed closed", e);
					}
				}
			}
		}
Пример #22
0
        protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
        {
            //BACKGROUND SERVICE
            var auth = new KiwiLoginService ();
            var fetchEvent = auth.GetEvent(authtoken, eventID);
            try{

                Task.WaitAll(fetchEvent);
                var singleEvent = fetchEvent.Result;

                activity.thisEvent = singleEvent;

                try {

                    URL url = new URL(singleEvent.PictureUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.OpenConnection();
                    conn.DoInput = true;
                    conn.Connect();
                    Stream stream = conn.InputStream;
                    Bitmap bmImg = BitmapFactory.DecodeStream(stream);

                    ImageView eventpic = (ImageView)activity.FindViewById(Resource.Id.eventPageEventImage);
                    eventpic.SetImageBitmap(bmImg);

                }
                catch (System.IO.IOException e)
                {
                    return null;
                }

            } catch (Exception e) {
                System.Console.WriteLine("-----Error pulling event data-----");
            }

            Intent intent = new Intent (activity, typeof(EventPageActivity));

            return intent;
        }
		/// <summary>
		/// Creates, configures and processes an asynchronous request to the indicated resource.
		/// </summary>
		/// <returns>Task in which the request is executed</returns>
		/// <param name="request">Request provided by <see cref="System.Net.Http.HttpClient"/></param>
		/// <param name="cancellationToken">Cancellation token.</param>
		protected override async Task <HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
		{
			AssertSelf ();
			if (request == null)
				throw new ArgumentNullException (nameof (request));
			
			if (!request.RequestUri.IsAbsoluteUri)
				throw new ArgumentException ("Must represent an absolute URI", "request");

			/*using (*/java_url = new URL (request.RequestUri.ToString ());/*) {*/
				/*using (*/java_connection = java_url.OpenConnection ();/*) {*/
					HttpURLConnection httpConnection = SetupRequestInternal (request, java_connection);
					return await ProcessRequest (request, httpConnection, cancellationToken);
				/*}
			}*/
		}