public Response <UIImage> Load(Uri uri, bool localCacheOnly) { NSUrl url = NSUrl.FromString(uri.AbsoluteUri); var cachePolicy = localCacheOnly ? NSUrlRequestCachePolicy.ReturnCacheDataDoNotLoad : NSUrlRequestCachePolicy.ReturnCacheDataElseLoad; var request = new NSUrlRequest(url, cachePolicy, 20); NSCachedUrlResponse cachedResponse = NSUrlCache.SharedCache.CachedResponseForRequest(request); if (cachedResponse != null) { return(new Response <UIImage>(cachedResponse.Data.AsStream(), true, cachedResponse.Data.Length)); } NSUrlResponse response; NSError error; NSData data = NSUrlConnection.SendSynchronousRequest(request, out response, out error); if (error != null || data == null) { return(null); } cachedResponse = new NSCachedUrlResponse(response, data, null, NSUrlCacheStoragePolicy.Allowed); NSUrlCache.SharedCache.StoreCachedResponse(cachedResponse, request); return(new Response <UIImage>(data.AsStream(), false, data.Length)); }
static bool SendRequest(NSUrlRequest request) { NSUrlResponse response = null; NSError error = null; NSData data = NSUrlConnection.SendSynchronousRequest(request, out response, out error); return(true); }
public override void StartLoading() { NSUrlResponse response = null; NSError error = null; NSData data = NSUrlConnection.SendSynchronousRequest(Request, out response, out error); if (response != null) { Client.ReceivedResponse(this, response, NSUrlCacheStoragePolicy.NotAllowed); } Client.DataLoaded(this, data); Client.FinishedLoading(this); }
static bool Download(Uri uri, string target) { try { NSUrlResponse response; NSError error; var req = new NSUrlRequest(new NSUrl(uri.ToString()), NSUrlRequestCachePolicy.UseProtocolCachePolicy, 120); var data = NSUrlConnection.SendSynchronousRequest(req, out response, out error); return(data.Save(target, true, out error)); } catch (Exception e) { Console.WriteLine("Problem with {0} {1}", uri, e); return(false); } }
/// <summary> /// Basic post request. /// </summary> /// <returns>The post response.</returns> /// <param name="url">URL.</param> /// <param name="args">Arguments.</param> /// <param name="headers">Headers.</param> public static string BasicPostRequest(string url, Dictionary <string, string> args, Dictionary <string, string> headers = null) { NSString urlString = (NSString)url; NSMutableUrlRequest request = new NSMutableUrlRequest(); request.Url = new NSUrl(urlString); request.HttpMethod = "POST"; string boundary = "---------------------------14737809831466499882746641449"; NSString contentType = new NSString(string.Format("multipart/form-data; boundary={0}", boundary)); var keys = new List <object> { "Content-Type" }; var objects = new List <object> { contentType }; if (headers != null) { foreach (KeyValuePair <string, string> kvp in headers) { keys.Add(kvp.Key); objects.Add(kvp.Value); } } var dictionary = NSDictionary.FromObjectsAndKeys(objects.ToArray(), keys.ToArray()); request.Headers = dictionary; NSMutableData body = new NSMutableData(); foreach (KeyValuePair <string, string> kvp in args) { body.AppendData(NSData.FromString(new NSString(string.Format("\r\n--{0}\r\n", boundary)))); body.AppendData(NSData.FromString(new NSString(string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", kvp.Key)))); body.AppendData(NSData.FromString(new NSString(kvp.Value))); body.AppendData(NSData.FromString(new NSString(string.Format("\r\n--{0}--\r\n", boundary)))); } request.Body = body; NSUrlResponse resp; NSError err; NSData returnData = NSUrlConnection.SendSynchronousRequest(request, out resp, out err); return(NSString.FromData(returnData, NSStringEncoding.UTF8).ToString()); }
private void Do_NSUrlConnection() { //NSUrlConnection urlConnection; //string localFilename = Path.GetTempPath() + Path.GetFileName(url); UIAlertView alertView = null; try { NSUrlResponse response = null; NSError error = null; NSUrlRequest urlRequest = new NSUrlRequest(new NSUrl(url), NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, 120); NSData data = NSUrlConnection.SendSynchronousRequest(urlRequest, out response, out error); if (data == null) { alertView = new UIAlertView("Error", "NSUrlConnection.SendSynchronousRequest returned null\n" + error.LocalizedDescription, null, "Ok", null); } else { NSString dataString = NSString.FromData(data, NSStringEncoding.ASCIIStringEncoding); if (dataString == null) { alertView = new UIAlertView("Error", "NSString.FromData returned null", null, "Ok", null); } else { alertView = new UIAlertView("Success", dataString.ToString(), null, "Ok", null); } } } catch (Exception e) { if (alertView == null) { alertView = new UIAlertView("Error", e.Message, null, "Ok", null); } Console.WriteLine(e.Message); } alertView.Show(); //ProxyTest_NSUrlConnectionDelegate connectionDelegate = new ProxyTest_NSUrlConnectionDelegate(); //urlConnection = new NSUrlConnection(DownloadRequest, connectionDelegate, true); }
/// <summary> /// Basic get request. /// </summary> /// <returns>The get response</returns> /// <param name="url">URL.</param> /// <param name="args">Arguments.</param> /// <param name="headers">Headers.</param> public static string BasicGetRequest(string url, Dictionary <string, string> args, Dictionary <string, string> headers = null) { NSMutableUrlRequest request = new NSMutableUrlRequest(); request.HttpMethod = "GET"; var keys = new List <object>(); var objects = new List <object>(); if (headers != null) { foreach (KeyValuePair <string, string> kvp in headers) { keys.Add(kvp.Key); objects.Add(kvp.Value); } } var dictionary = NSDictionary.FromObjectsAndKeys(objects.ToArray(), keys.ToArray()); request.Headers = dictionary; NSMutableData body = new NSMutableData(); if (args.Count > 0) { url = url + "?"; int i = 0; foreach (KeyValuePair <string, string> kvp in args) { i++; url = url + kvp.Key + "=" + System.Net.WebUtility.HtmlEncode(kvp.Value); if (i < args.Count) { url = url + "&"; } } } request.Url = new NSUrl(url); request.Body = body; NSUrlResponse resp; NSError err; NSData returnData = NSUrlConnection.SendSynchronousRequest(request, out resp, out err); return(NSString.FromData(returnData, NSStringEncoding.UTF8).ToString()); }
public void ReloadData(TKAutoCompleteTextView autocomplete) { NSMutableArray suggestions = new NSMutableArray(); if (airports == null) { NSUrl url = new NSUrl(urlStr); NSUrlRequest req = new NSUrlRequest(url); NSUrlResponse res; NSData dataVal = new NSData(); NSDictionary jsonResult = new NSDictionary(); NSError error; NSError errorReq; dataVal = NSUrlConnection.SendSynchronousRequest(req, out res, out errorReq); if (dataVal != null) { jsonResult = (NSDictionary)NSJsonSerialization.Deserialize(dataVal, NSJsonReadingOptions.MutableContainers, out error); if (error == null) { airports = (NSArray)jsonResult.ObjectForKey(new NSString("airports")); } for (nuint i = 0; i < airports.Count; i++) { NSDictionary item = airports.GetItem <NSDictionary> (i); NSString name = (NSString)item.ValueForKey(new NSString("FIELD2")); NSString shortName = (NSString)item.ValueForKey(new NSString("FIELD5")); string result = String.Format("{0}, {1}", name.ToString(), shortName.ToString()); if (result.ToUpper().StartsWith(prefix.ToUpper())) { suggestions.Add(new TKAutoCompleteToken(new NSString(result))); } } } DispatchQueue queue = DispatchQueue.MainQueue; queue.DispatchAfter(DispatchTime.Now, delegate { autocomplete.CompleteSuggestionViewPopulation(suggestions); }); } }
public void CheckNetworkConnection() { NSString urlString = new NSString("https://captive.apple.com"); NSUrl url = new NSUrl(urlString); NSUrlRequest request = new NSUrlRequest(url, NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 3); NSData data = NSUrlConnection.SendSynchronousRequest(request, out NSUrlResponse response, out NSError error); NSString result = NSString.FromData(data, NSStringEncoding.UTF8); if (result.Contains(new NSString("Success"))) { IsConnected = true; } else { IsConnected = false; } }
// Preform the download private void Download(bool isAsync, string path) { _stringBuilder.Clear(); NSMutableUrlRequest request = null; NSError error = null; try { #if DEBUG DateTime start = DateTime.Now; #endif request = new NSMutableUrlRequest(new NSUrl(_url), NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, _timeout); if (_post != String.Empty) { request.HttpMethod = "POST"; request["Content-Length"] = _post.Length.ToString();; request["Content-Type"] = "application/x-www-form-urlencoded"; request.Body = _post; } if (isAsync) { DataDownloader_NSUrlConnectionDelegate connectionDelegate = new DataDownloader_NSUrlConnectionDelegate(); connectionDelegate.AsyncDownloadComplete += delegate(object sender, AsyncDownloadComplete_EventArgs e) { if (path != String.Empty) { ((DataDownloader_NSUrlConnectionDelegate)sender).WriteResultToFile(path); } if (AsyncDownloadComplete != null) { AsyncDownloadComplete(this, e); } }; if (AsyncDownloadProgressChanged != null) { connectionDelegate.AsyncDownloadProgressChanged += delegate(object sender, AsyncDownloadProgressChanged_EventArgs e) { AsyncDownloadProgressChanged(this, e); }; } connectionDelegate.AsyncDownloadFailed += delegate(object sender, AsyncDownloadFailed_EventArgs e) { _exception = new Exception(e.Error.LocalizedDescription); if (AsyncDownloadFailed != null) { AsyncDownloadFailed(this, e); } }; // Not using matching functions, but I'll live. //NSUrlConnection.SendAsynchronousRequest(request, new NSOperationQueue(), connectionDelegate); _connection = new NSUrlConnection(request, connectionDelegate, true); } else { NSUrlResponse response = null; NSData output = NSUrlConnection.SendSynchronousRequest(request, out response, out error); if (output == null) { if (error != null) { _exception = new Exception(error.LocalizedDescription); } else if (response == null) { _exception = new Exception("Could not get a response from the server."); } else { _exception = new Exception("Could not get data from server."); } } if (path != String.Empty) { File.WriteAllText(path, output.ToString()); } _stringBuilder = new StringBuilder(output.ToString()); Console.WriteLine(_stringBuilder.ToString()); } #if DEBUG Console.WriteLine("NSData.FromUrl: " + (DateTime.Now - start).TotalMilliseconds); start = DateTime.Now; #endif } catch (Exception err) { _exception = err; Console.WriteLine("StreamLoading Error: " + err.Message); } finally { } }
/// <summary> /// Upload function using the native functionality of Mac /// </summary> /// <returns>Response string</returns> /// <param name="url">URL.</param> /// <param name="paramFileBytes">Parameter file bytes.</param> /// <param name="fileFormName">File form name.</param> /// <param name="args">Arguments.</param> private static string UploadNative(string url, byte [] paramFileBytes, string fileFormName, Dictionary <string, string> args = null, Dictionary <string, string> headers = null, bool onlyData = false) { NSData actualFile = NSData.FromArray(paramFileBytes); NSString urlString = (NSString)url; //we're gonna send byte data NSMutableUrlRequest request = new NSMutableUrlRequest(); request.Url = new NSUrl(urlString); request.HttpMethod = "POST"; string boundary = "---------------------------14737809831466499882746641449"; NSString contentType = new NSString(string.Format("multipart/form-data; boundary={0}", boundary)); var keys = new List <object> { "Content-Type" }; var objects = new List <object> { contentType }; foreach (KeyValuePair <string, string> kvp in headers) { if (!keys.Contains(kvp.Key)) { keys.Add(kvp.Key); objects.Add(kvp.Value); } else { for (int i = 0; i < keys.Count; i++) { if ((string)keys [i] == kvp.Key) { objects [i] = kvp.Value; } } } } var dictionary = NSDictionary.FromObjectsAndKeys(objects.ToArray(), keys.ToArray()); request.Headers = dictionary; NSMutableData body = new NSMutableData(); if (!onlyData) { body.AppendData(NSData.FromString(new NSString(string.Format("\r\n--{0}\r\n", boundary)))); body.AppendData(NSData.FromString(new NSString(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{0}.png\"\r\n", fileFormName)))); body.AppendData(NSData.FromString(new NSString("Content-Type: application/octet-stream\r\n\r\n"))); } body.AppendData(actualFile); if (!onlyData) { body.AppendData(NSData.FromString(new NSString(string.Format("\r\n--{0}--\r\n", boundary)))); foreach (KeyValuePair <string, string> kvp in args) { body.AppendData(NSData.FromString(new NSString(string.Format("\r\n--{0}\r\n", boundary)))); body.AppendData(NSData.FromString(new NSString(string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", kvp.Key)))); body.AppendData(NSData.FromString(new NSString(kvp.Value))); body.AppendData(NSData.FromString(new NSString(string.Format("\r\n--{0}--\r\n", boundary)))); } } //Attach body request.Body = body; NSUrlResponse resp; NSError err; NSData returnData = NSUrlConnection.SendSynchronousRequest(request, out resp, out err); return(NSString.FromData(returnData, NSStringEncoding.UTF8).ToString()); }