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); }
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; } }
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); } } } }
private static void DownloadImage(object state) { try { var info = (ImageDownloadInfo)state; Bitmap bitmap; lock (UrlToImageMap) { if (UrlToImageMap.ContainsKey(info.ImageUrl)) { bitmap = UrlToImageMap[info.ImageUrl]; } else { var imageUrl = new URL(info.ImageUrl); bitmap = BitmapFactory.DecodeStream(imageUrl.OpenStream()); UrlToImageMap.Add(info.ImageUrl, bitmap); } } info.Context.RunOnUiThread(() => info.ImageView.SetImageBitmap(bitmap)); } catch (Exception) { // Log error, etc } }
/// <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); }
/// <summary> /// Download a resource from the specified URI. /// </summary> public byte[] DownloadData(URL address) { URLConnection connection = null; InputStream inputStream = null; try { connection = OpenConnection(address); inputStream = connection.InputStream; var memStream = new ByteArrayOutputStream(); var buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0) { memStream.Write(buffer, 0, len); } return memStream.ToByteArray(); } finally { if (inputStream != null) inputStream.Close(); var httpConnection = connection as HttpURLConnection; if (httpConnection != null) httpConnection.Disconnect(); } }
public static async Task <string> GetPulsePin() { string pin = await Task.Run(async() => { string pulsePin = null; // Create a URL for the desired page URL url = new Java.Net.URL("https://ares-project.uk/showpin.php?action=getbuildpin"); // Read all the text returned by the server using (Java.IO.BufferedReader input = new Java.IO.BufferedReader(new Java.IO.InputStreamReader(url.OpenStream()))) { string s1 = null; while ((s1 = await input.ReadLineAsync()) != null) { if (s1.Contains("Pin = ")) { pulsePin = s1.Substring(s1.IndexOf("Pin = "), 10).Substring(6, 4); break; } } } return(pulsePin); }); return(pin); }
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 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); }
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()); } }
protected override Bitmap RunInBackground(params string[] @params) { string urldisplay = @params[0]; Bitmap mIcon11 = null; try { var ipn = new Java.Net.URL(urldisplay).OpenStream(); mIcon11 = BitmapFactory.DecodeStream(ipn); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } return(mIcon11); }
/// <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 }
// 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); })); } }
private void DownloadBitmap(string url) { if (BitmapCache.Contains(url)) { return; } try { using (var connection = new URL(url).OpenConnection()) { connection.Connect(); using (var input = connection.InputStream) { BitmapCache.Add(url, BitmapFactory.DecodeStream(input)); } } } catch { /// Do nothing for now } }
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; } }
/// <summary> /// Download a resource from the specified URI. /// </summary> public Task<byte[]> DownloadDataTaskAsync(URL address) { return Task.Factory.StartNewIO(() => DownloadData(address)); }
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); } } } }
/** 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; }
/// <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 (); }
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 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 ? 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(';')); } if (Timeout != null) { var clientBuilder = client.NewBuilder(); var timeout = (long)Timeout.Value.TotalSeconds; clientBuilder.ConnectTimeout(timeout, TimeUnit.Seconds); clientBuilder.WriteTimeout(timeout, TimeUnit.Seconds); clientBuilder.ReadTimeout(timeout, TimeUnit.Seconds); client = clientBuilder.Build(); } 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); }
/// <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; }
/// <summary> /// Downloads the resource with the specified URI to a local file. /// </summary> public void DownloadFile(URL address, string fileName) { URLConnection connection = null; InputStream inputStream = null; OutputStream outputStream = new FileOutputStream(fileName); try { connection = OpenConnection(address); inputStream = connection.InputStream; var buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0) { outputStream.Write(buffer, 0, len); } outputStream.Flush(); } finally { if (inputStream != null) inputStream.Close(); var httpConnection = connection as HttpURLConnection; if (httpConnection != null) httpConnection.Disconnect(); outputStream.Close(); } }
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; } }
/// <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 }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (Timeout != null) { var timeout = (long)Timeout.Value.TotalMilliseconds; client.SetConnectTimeout(timeout, TimeUnit.Milliseconds); client.SetWriteTimeout(timeout, TimeUnit.Milliseconds); client.SetReadTimeout(timeout, TimeUnit.Milliseconds); } 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; }
/// <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); /*} }*/ }
private Bitmap LoadImage(string imageUrl) { var url= new URL (imageUrl); var imageBitmap = BitmapFactory.DecodeStream (url.OpenConnection ().InputStream); return imageBitmap; }
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; } }
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> /// Download a string from the specified URI. /// </summary> public string DownloadString(URL address) { URLConnection connection = null; InputStream inputStream = null; try { connection = OpenConnection(address); inputStream = connection.InputStream; var reader = new InputStreamReader(inputStream); var buffer = new char[BUFFER_SIZE]; var builder = new StringBuilder(); int len; while ((len = reader.Read(buffer, 0, BUFFER_SIZE)) > 0) { builder.Append(buffer, 0, len); } return builder.ToString(); } finally { if (inputStream != null) inputStream.Close(); var httpConnection = connection as HttpURLConnection; if (httpConnection != null) httpConnection.Disconnect(); } }
/// <summary> /// Download a resource from the specified URI. /// </summary> public Task<string> DownloadStringTaskAsync(URL address) { return Task.Factory.StartNewIO(() => DownloadString(address)); }
/// <inheritdoc /> protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { 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); if (bytes.Length > 0 || request.Method != HttpMethod.Get) { 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 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(name, values) in keyValuePairs) { var headerSeparator = name == "User-Agent" ? " " : ","; builder.AddHeader(name, string.Join(headerSeparator, values)); } cancellationToken.ThrowIfCancellationRequested(); var rq = builder.Build(); var call = _client.Value.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 (Javax.Net.Ssl.SSLException ex) { throw new HttpRequestException(ex.Message, new AuthenticationException(ex.Message, ex)); } catch (Java.Net.SocketTimeoutException ex) { throw new TaskCanceledException(ex.Message, ex); } catch (Java.IO.IOException ex) { throw new HttpRequestException(ex.Message, ex); } var respBody = resp.Body(); cancellationToken.ThrowIfCancellationRequested(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()) { RequestMessage = request, ReasonPhrase = resp.Message() }; ret.RequestMessage.RequestUri = new Uri(resp.Request().Url().Url().ToString()); // should point to the request leading to the final response (in case of redirects) if (respBody != null) { ret.Content = new StreamContent(respBody.ByteStream()); } else { ret.Content = new ByteArrayContent(new byte[0]); } foreach (var(name, values) in resp.Headers().ToMultimap()) { // special handling for Set-Cookie because folding them into one header is strongly discouraged. // but adding them just folds them again so this is no option at the moment ret.Headers.TryAddWithoutValidation(name, values); ret.Content.Headers.TryAddWithoutValidation(name, values); } return(ret); }
/// <summary> /// Downloads the resource with the specified URI to a local file. /// </summary> public Task DownloadFileTaskAsync(URL address, string fileName) { return Task.Factory.StartNewIO(() => DownloadFileTaskAsync(address, fileName)); }
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 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.Url(); 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(); } 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 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"); }
protected override void Dispose (bool disposing) { disposed = true; if (java_connection != null) { java_connection.Dispose (); java_connection = null; } if (java_url != null) { java_url.Dispose (); java_url = null; } base.Dispose (disposing); }
//*************************************************************************************************** //******************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)); }