/// <summary> /// Метод заполняет коллекцию заданных сущностей в модели представления, /// оправляя асинхронный GET-запрос к REST-сервису. /// Извлекаются потомки заданного родителя. /// </summary> /// <typeparam name="TParent">Тип родителя</typeparam> /// <typeparam name="TChild">Тип потомков</typeparam> /// <param name="parentId">Идентификатор родителя</param> protected void SelectByParentAsync <TParent, TChild>(int parentId) { var serializer = new DataContractJsonSerializer(typeof(TChild[])); string parentEntityName = typeof(TParent).Name; string childEntityName = typeof(TChild).Name; HttpWebRequest httpWebRequest = WebRequest.CreateHttp( RestServiceAddress + parentEntityName + "/" + parentId + "/" + childEntityName); httpWebRequest.Method = "GET"; var r = httpWebRequest.BeginGetResponse(asyncResult => { var request = (HttpWebRequest)asyncResult.AsyncState; var response = (HttpWebResponse)request.EndGetResponse(asyncResult); try { var entityArray = (TChild[])serializer.ReadObject(response.GetResponseStream()); var entityObservableCollection = new ObservableCollection <TChild>(entityArray); if (typeof(TChild) == typeof(Order)) { var entityViewModel = new OrderViewModel() { Orders = entityObservableCollection as ObservableCollection <Order> }; } else if (typeof(TChild) == typeof(Product)) { var entityViewModel = new ProductViewModel() { Products = entityObservableCollection as ObservableCollection <Product> }; } else if (typeof(TChild) == typeof(ProductDescriptor)) { var entityViewModel = new ProductDescriptorViewModel() { ProductDescriptors = entityObservableCollection as ObservableCollection <ProductDescriptor> }; } } catch (Exception) { if (typeof(TChild) == typeof(Order)) { var entityViewModel = new OrderViewModel() { Orders = null }; } else if (typeof(TChild) == typeof(Product)) { var entityViewModel = new ProductViewModel() { Products = null }; } else if (typeof(TChild) == typeof(ProductDescriptor)) { var entityViewModel = new ProductDescriptorViewModel() { ProductDescriptors = null }; } } RaisePropertyChanged("SelectByParentAsyncCompleted"); }, httpWebRequest); }
/// <summary> /// Creates a new store based on the given template /// </summary> /// <param name="template">Template</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> /// <remarks> /// <para> /// Template must inherit from <see cref="BaseStardogTemplate"/> /// </para> /// </remarks> public void CreateStore(IStoreTemplate template, AsyncStorageCallback callback, object state) { if (template is BaseStardogTemplate) { //POST /admin/databases //Creates a new database; expects a multipart request with a JSON specifying database name, options and filenames followed by (optional) file contents as a multipart POST request. try { //Get the Template BaseStardogTemplate stardogTemplate = (BaseStardogTemplate)template; IEnumerable <String> errors = stardogTemplate.Validate(); if (errors.Any()) { throw new RdfStorageException("Template is not valid, call Validate() on the template to see the list of errors"); } JObject jsonTemplate = stardogTemplate.GetTemplateJson(); Console.WriteLine(jsonTemplate.ToString()); //Create the request and write the JSON HttpWebRequest request = this.CreateAdminRequest("databases", MimeTypesHelper.Any, "POST", new Dictionary <string, string>()); String boundary = StorageHelper.HttpMultipartBoundary; #if !SILVERLIGHT byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); byte[] terminatorBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); #else //Should be safe to do this for Silverlight as everything here would be in the ASCII range anyway byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] terminatorBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); #endif request.ContentType = MimeTypesHelper.FormMultipart + "; boundary=" + boundary; request.BeginGetRequestStream(r => { try { using (Stream stream = request.EndGetRequestStream(r)) { //Boundary stream.Write(boundaryBytes, 0, boundaryBytes.Length); //Then the root Item String templateItem = String.Format(StorageHelper.HttpMultipartContentTemplate, "root", jsonTemplate.ToString()); byte[] itemBytes = System.Text.Encoding.UTF8.GetBytes(templateItem); stream.Write(itemBytes, 0, itemBytes.Length); //Then terminating boundary stream.Write(terminatorBytes, 0, terminatorBytes.Length); stream.Close(); } Tools.HttpDebugRequest(request); //Make the request request.BeginGetResponse(r2 => { try { using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2)) { Tools.HttpDebugResponse(response); //If we get here it completed OK response.Close(); } callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID), state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleHttpError(webEx, "creating a new Store '" + template.ID + "' asynchronously in")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(ex, "creating a new Store '" + template.ID + "' asynchronously in")), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleHttpError(webEx, "creating a new Store '" + template.ID + "' asynchronously in")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(ex, "creating a new Store '" + template.ID + "' asynchronously in")), state); } }, state); } catch (WebException webEx) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleHttpError(webEx, "creating a new Store '" + template.ID + "' asynchronously in")), state); } catch (Exception ex) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(ex, "creating a new Store '" + template.ID + "' asynchronously in")), state); } } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, new RdfStorageException("Invalid template, templates must derive from BaseStardogTemplate")), state); } }
async Task <string> SendRequestAndGetJsonResponseClassicHttpWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { LoggingMethod.WriteToLog(string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseClassicHttpWithPOST", DateTime.Now.ToString()), pubnubConfig.LogVerbosity); var taskComplete = new TaskCompletionSource <string>(); try { request.Method = "POST"; request.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes(postData); //request.ContentLength = data.Length; #if !NET35 && !NET40 && !NET45 && !NET461 using (var requestStream = await Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, pubnubRequestState)) { requestStream.Write(data, 0, data.Length); requestStream.Flush(); } #else using (var requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); requestStream.Flush(); } #endif IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback( (asynchronousResult) => { RequestState <T> asyncRequestState = asynchronousResult.AsyncState as RequestState <T>; HttpWebRequest asyncWebRequest = asyncRequestState.Request as HttpWebRequest; if (asyncWebRequest != null) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before EndGetResponse With POST ", DateTime.Now.ToString())); HttpWebResponse asyncWebResponse = (HttpWebResponse)asyncWebRequest.EndGetResponse(asynchronousResult); asyncRequestState.Response = asyncWebResponse; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, After EndGetResponse With POST ", DateTime.Now.ToString())); using (StreamReader streamReader = new StreamReader(asyncWebResponse.GetResponseStream())) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Inside StreamReader With POST ", DateTime.Now.ToString())); //Need to return this response string jsonString = streamReader.ReadToEnd(); asyncRequestState.GotJsonResponse = true; System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST ", DateTime.Now.ToString())); taskComplete.TrySetResult(jsonString); } if (asyncRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif asyncRequestState.Response = null; asyncRequestState.Request = null; } } } ), pubnubRequestState); Timer webRequestTimer = new Timer(OnPubnubWebRequestTimeout <T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); return(taskComplete.Task.Result); } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 await Task.Factory.StartNew(() => { }); string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST from WebException response", DateTime.Now.ToString())); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { taskComplete.TrySetException(ex); } return(""); } catch (Exception ex) { taskComplete.TrySetException(ex); return(""); } }
public void download(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { // source, target, trustAllHosts, this._id, headers string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; downloadOptions.FilePath = optionStrings[1]; bool trustAll = false; bool.TryParse(optionStrings[2], out trustAll); downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[3]; downloadOptions.Headers = optionStrings[4]; downloadOptions.CallbackId = callbackId = optionStrings[5]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { // is the URL a local app file? if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // just copy from one area of iso-store to another ... if (isoFile.FileExists(downloadOptions.Url)) { isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); } else { // need to unpack resource from the dll string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", ""); Uri uri = new Uri(cleanUrl, UriKind.Relative); var resource = Application.GetResourceStream(uri); if (resource != null) { // create the file destination if (!isoFile.FileExists(downloadOptions.FilePath)) { var destFile = isoFile.CreateFile(downloadOptions.FilePath); destFile.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = resource.Stream.Length; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(resource.Stream)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } } } } } } } } File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId); } return; } else { // otherwise it is web-bound, we will actually download it //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } try { webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } catch (WebException) { // eat it } // dispatch an event for progress ( 0 ) lock (state) { if (!state.isCancelled) { var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress()); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } }
private void BeginGetFile(bool acceptRange) { var tempFileSize = 0L; if (File.Exists(this.tempFile)) { tempFileSize = new FileInfo(this.tempFile).Length; var outDated = this.remoteLastModifiedTime > this.localLastModifiedTime; if (outDated) { File.Delete(this.tempFile); } else { if (tempFileSize == this.remoteFileSize) { MoveFile(this.tempFile, this.localFile); //完成 return; } else if (tempFileSize > this.remoteFileSize) { File.Delete(this.tempFile); } } } if (File.Exists(this.localFile)) { try { File.Delete(this.localFile); } catch (Exception e) { DebugEx.LogWarning(e); } } HttpWebRequest request = null; try { request = (HttpWebRequest)HttpWebRequest.Create(this.remoteFile); request.ServicePoint.ConnectionLimit = MaxConnectLimit; request.ServicePoint.Expect100Continue = false; request.Timeout = 3000; if (tempFileSize != 0L && acceptRange) { request.AddRange((int)tempFileSize, (int)this.remoteFileSize - 1); } request.Method = WebRequestMethods.Http.Get; request.BeginGetResponse(this.OnGetFile, request); } catch (System.Exception ex) { DebugEx.LogError(ex); if (request != null) { request.Abort(); request = null; } } }
private dynamic odooServerCall <T>(string url, JsonRpcRequestParameter parameter) { var tmpData = new JsonRpcRequest(parameter); string requestContent = ""; // this.Password = Settings.UserPassword; if (Device.RuntimePlatform == "Android") { requestContent = JsonConvert.SerializeObject(tmpData); } else { Dictionary <string, dynamic> paramsDic = new Dictionary <string, dynamic>(); paramsDic.Add("service", parameter.Service); paramsDic.Add("method", parameter.Method); paramsDic.Add("args", parameter.Argument); Dictionary <string, dynamic> jObj = new Dictionary <string, dynamic>(); jObj.Add("jsonrpc", "2.0"); jObj.Add("method", "call"); jObj.Add("params", paramsDic); var formatData = JsonConvert.SerializeObject(jObj); requestContent = formatData; } System.Diagnostics.Debug.WriteLine("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW " + requestContent); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); request.ContentType = "application/json"; request.Method = "POST"; try { App.responseState = true; App.NetAvailable = true; IAsyncResult resultRequest = request.BeginGetRequestStream(null, null); Stream streamInput = request.EndGetRequestStream(resultRequest); byte[] byteArray = Encoding.UTF8.GetBytes(requestContent); streamInput.WriteAsync(byteArray, 0, byteArray.Length); streamInput.FlushAsync(); // Receive data from server IAsyncResult resultResponse = request.BeginGetResponse(null, null); HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(resultResponse); Stream streamResponse = response.GetResponseStream(); StreamReader streamRead = new StreamReader(streamResponse); var resultData = streamRead.ReadToEndAsync(); var responseData = resultData.Result; streamResponse.FlushAsync(); if (Device.RuntimePlatform == "iOS") { string rspData = string.Join("", responseData); try { JObject jsonObj = JObject.Parse(rspData); Dictionary <string, dynamic> dictObj = jsonObj.ToObject <Dictionary <string, dynamic> >(); return(dictObj["result"]); } catch (Exception ea) { return(responseData); } } else { try { JsonRpcResponse <T> jsonRpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(responseData); if (jsonRpcResponse.Error != null) { return("Odoo Error"); } else { return(jsonRpcResponse.Result); } } catch (Exception ea) { return(responseData); } } } catch (Exception ea) { if (ea.Message.Contains("(Network is unreachable)") || ea.Message.Contains("NameResolutionFailure")) { App.NetAvailable = false; } else if (ea.Message.Contains("(503) Service Unavailable")) { App.responseState = false; } System.Diagnostics.Debug.WriteLine(ea.Message); // throw; } return(default(T)); }
protected virtual void ExecuteRequestWithoutBody(HttpWebRequest request) { request.BeginGetResponse(ProcessCallback(action.Success, action.Fail), request); }
void getRequest(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.BeginGetResponse(OnAsyncCallback, request); }
/// <summary> /// Parses the passed in MediaStream to find the first frame and signals /// to its parent MediaElement that it is ready to begin playback by calling /// ReportOpenMediaCompleted. /// </summary> protected override void OpenMediaAsync() { System.Diagnostics.Debug.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + ": OpenMediaAsync()"); // So, here is why this is a little weird. // The Shoutcast server software has the ability to provide web pages. These pages just happen to be served from the SAME address as the media stream. // Putting a "/;" at the end of the Uri will tell the Shoutcast server that we aren't a web browser, so stream the data. The problem is that not ALL // Shoutcast servers are configured that way. So, we have to do a request to get the content type. If it is text/html, we append the "/;" and move on. // If it is an empty string, 99.9% of the time, this will be the media stream (If it's an ICY stream, the ICY "headers" don't parse properly). The ShoutcastStream // will handle this case, so we let it go through. HttpWebRequest contentTypeRequest = ShoutcastMediaStreamSource.CreateHttpWebRequest(this.StreamUri, this.IncludeMetadata); contentTypeRequest.BeginGetResponse( ia1 => { HttpWebRequest req1 = ia1.AsyncState as HttpWebRequest; try { HttpWebResponse res1 = (HttpWebResponse)req1.EndGetResponse(ia1); string contentType = res1.ContentType; if ((contentType == string.Empty) || (contentType == "audio/mpeg") || contentType == "audio/x-mpegurl") { try { this.audioStream = new ShoutcastStream(this, res1); this.audioStreamDescription = this.audioStream.AudioStreamDescription; this.ReportOpenMediaCompleted(this.audioStream.AudioSourceAttributes, new MediaStreamDescription[] { this.audioStream.AudioStreamDescription }); } catch (Exception ex) { this.CleanupAudioStream(); this.ErrorOccurred(ex.Message); } } else { // Close the original response. We need another one. res1.Close(); res1 = null; if (!this.StreamUri.OriginalString.EndsWith("/", StringComparison.Ordinal)) { this.StreamUri = new Uri(this.StreamUri.OriginalString + "/;", UriKind.Absolute); } else { this.StreamUri = new Uri(this.StreamUri.OriginalString + ";", UriKind.Absolute); } HttpWebRequest streamRequest = ShoutcastMediaStreamSource.CreateHttpWebRequest(this.StreamUri, this.IncludeMetadata); streamRequest.BeginGetResponse( ia => { HttpWebRequest req = ia.AsyncState as HttpWebRequest; try { HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(ia); this.audioStream = new ShoutcastStream(this, res); this.audioStreamDescription = this.audioStream.AudioStreamDescription; this.ReportOpenMediaCompleted(this.audioStream.AudioSourceAttributes, new MediaStreamDescription[] { this.audioStream.AudioStreamDescription }); } catch (Exception ex) { if (res1 != null) { res1.Close(); } this.CleanupAudioStream(); this.ErrorOccurred(ex.Message); } }, streamRequest); } } catch (Exception ex) { this.CleanupAudioStream(); this.ErrorOccurred(ex.Message); } }, contentTypeRequest); }
internal static void GetToken(SocialType type, ClientInfo client, string code, Action <AccessToken> action) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GetTokenUrl(type, client, code)); httpWebRequest.Method = "POST"; httpWebRequest.BeginGetResponse((p) => { HttpWebRequest request = (HttpWebRequest)p.AsyncState; HttpWebResponse httpWebResponse; try { httpWebResponse = (HttpWebResponse)request.EndGetResponse(p); } catch (WebException ex) { return; } if (httpWebResponse != null) { using (var stream = httpWebResponse.GetResponseStream()) { AccessToken token = new AccessToken(); if (type == SocialType.Tencent) { using (var reader = new System.IO.StreamReader(stream)) { string text = reader.ReadToEnd(); if (!string.IsNullOrEmpty(text)) { //access_token=ec70e646177f025591e4282946c19b67&expires_in=604800&name=xshf12345 var acc = text.Split('&'); foreach (var item in acc) { var single = item.Split('='); if (single[0] == "access_token") { token.Token = single[1]; } else if (single[0] == "expires_in") { token.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToInt32(single[1])); } else if (single[0] == "name") { token.UserInfo = single[1]; } } token.OpenId = client.Tag; } } } else if (type == SocialType.Weibo) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Weibo.WeiboAccessToken)); var item = ser.ReadObject(stream) as Weibo.WeiboAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.uid; } else if (type == SocialType.Renren) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Renren.RenrenAccessToken)); var item = ser.ReadObject(stream) as Renren.RenrenAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.user.name; } string filePath = string.Format(SocialAPI.ACCESS_TOKEN_PREFIX, type.ToString()); JsonHelper.SerializeData <AccessToken>(filePath, token); action(token); } } }, httpWebRequest); }
public HttpRequest(string url, string method, string data, Action <object> successfulCallBack, Action <string> errorCallBack) : this(url, method) { string errorMsg = string.Empty; // Create POST data and convert it to a byte array. string postData = data; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. _request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. _request.ContentLength = byteArray.Length; _errorCallback = errorCallBack; try { System.Uri uri = new Uri(url); // Create a HttpWebrequest object to the desired URL. _request = (HttpWebRequest)WebRequest.Create(uri); _request.Method = method; // Create an instance of the RequestState and assign the previous myHttpWebRequest1 // object to it's request field. RequestState myRequestState = new RequestState(); myRequestState.request = _request; myRequestState.SuccessfulCallBack = successfulCallBack; myRequestState.ErrorCallback = errorCallBack; _request.BeginGetRequestStream((asyncResult) => { HttpWebRequest preq = (asyncResult.AsyncState as RequestState).request; if (preq != null) { Stream postStream = preq.EndGetRequestStream(asyncResult); postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); } // Start the asynchronous request. preq.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); allDone.WaitOne(); }, myRequestState); } catch (WebException e) { errorMsg += "\nException raised!\n"; errorMsg += "Message: "; errorMsg += e.Message; errorMsg += "\nStatus: "; errorMsg += e.Status; errorMsg += "\n"; } catch (Exception e) { errorMsg += "\nException raised!\n"; errorMsg += "\nMessage: "; errorMsg += e.Message; errorMsg += "\n"; } if (!string.IsNullOrEmpty(errorMsg)) { UnityEngine.Debug.Log(errorMsg); if (errorCallBack != null) { errorCallBack(errorMsg); } } }
private Task <string> CreateUploadJob(string createJobUri, Stream dataSourceStream, DataSourceFormat format) { var tcs = new TaskCompletionSource <string>(); //Include the data to geocode in the HTTP request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(createJobUri); // The HTTP method must be 'POST'. request.Method = "POST"; request.ContentType = "application/octet-stream"; request.ContinueTimeout = 1800000; request.BeginGetRequestStream((a) => { var r = (HttpWebRequest)a.AsyncState; using (var postStream = request.EndGetRequestStream(a)) { if (format == DataSourceFormat.SHP || XmlUtilities.IsStreamCompressed(dataSourceStream)) { dataSourceStream.CopyTo(postStream); } else { using (var zipStream = new GZipStream(postStream, CompressionMode.Compress)) { dataSourceStream.CopyTo(zipStream); } } } request.BeginGetResponse((a2) => { try { var r2 = (HttpWebRequest)a2.AsyncState; var response = (HttpWebResponse)r2.EndGetResponse(a2); string dataflowJobLocation = string.Empty; foreach (var hKey in response.Headers.AllKeys) { if (string.Compare(hKey, "Location", StringComparison.OrdinalIgnoreCase) == 0) { dataflowJobLocation = response.Headers[hKey]; break; } } tcs.SetResult(dataflowJobLocation); } catch (WebException ex) { if (ex.Response != null) { var ser = new DataContractJsonSerializer(typeof(DataflowResponse)); var res = ser.ReadObject(ex.Response.GetResponseStream()) as DataflowResponse; if (res.ErrorDetails != null && res.ErrorDetails.Length > 0) { tcs.SetException(new Exception(string.Join("\r\n", res.ErrorDetails))); return; } } tcs.SetException(ex); } }, request); }, request); return(tcs.Task); }
public void createRESTRequest(RESTRequest rest_request, string URI, string method, string body) { HttpWebRequest req = WebRequest.Create(new Uri(URI)) as HttpWebRequest; req.Method = method; req.Headers["Authorization"] = "OAuth " + OAuthConnection.AccessToken; req.Headers["User-Agent"] = "salesforce-toolkit/Windows7/20"; if (method == "POST" || method == "PATCH") { req.ContentType = "application/json"; req.BeginGetRequestStream( (result) => { HttpWebRequest request = (HttpWebRequest)result.AsyncState; System.IO.Stream postStream = request.EndGetRequestStream(result); string postData = body; byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData); // Write to the request stream. postStream.Write(byteArray, 0, postData.Length); postStream.Close(); // Start the asynchronous operation to get the response request.BeginGetResponse( (postresult) => { try { RESTResult restresult = new RESTResult(); restresult.request = rest_request; restresult.data = getHTTPResult(postresult, method); restresult.request.callback(restresult); } catch (WebException wex) { RESTResult restresult = new RESTResult(); restresult.request = rest_request; string error = handleHTTPError(wex); restresult.data = JObject.Parse(error.Substring(1, error.Length - 1)); restresult.message = (string)restresult.data["message"]; restresult.request.errorCallback(restresult); } }, req); }, req); } else { req.BeginGetResponse( (result) => { try { RESTResult restresult = new RESTResult(); restresult.request = rest_request; restresult.data = getHTTPResult(result, method); restresult.request.callback(restresult); } catch (WebException wex) { RESTResult restresult = new RESTResult(); restresult.request = rest_request; string error = handleHTTPError(wex); restresult.data = JObject.Parse(error.Substring(1, error.Length - 1)); restresult.message = (string)restresult.data["message"]; restresult.request.errorCallback(restresult); } }, req); } }
public void BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetResponse(null, null); }); }
public void SendRequest() { try { ServicePointManagerTimeoutSupport.ResetHosts(); Request = (HttpWebRequest)WebRequest.Create(Url); Request.Method = HttpMethod; Request.ContentType = HttpMIMEType; if (!HttpVerifyCert) { // We could hijack Connection Group Name to identify // a desired security exception. But at the moment we'll use a dummy header instead. // Request.ConnectionGroupName = "NoVerify"; Request.Headers.Add("NoVerifyCert", "true"); } // else // { // Request.ConnectionGroupName="Verify"; // } if (!HttpPragmaNoCache) { Request.Headers.Add("Pragma", "no-cache"); } if (HttpCustomHeaders != null) { for (int i = 0; i < HttpCustomHeaders.Count; i += 2) { Request.Headers.Add(HttpCustomHeaders[i], HttpCustomHeaders[i + 1]); } } if (!string.IsNullOrEmpty(proxyurl)) { if (!string.IsNullOrEmpty(proxyexcepts)) { string[] elist = proxyexcepts.Split(';'); Request.Proxy = new WebProxy(proxyurl, true, elist); } else { Request.Proxy = new WebProxy(proxyurl, true); } } if (ResponseHeaders != null) { foreach (KeyValuePair <string, string> entry in ResponseHeaders) { if (entry.Key.Equals("user-agent", StringComparison.OrdinalIgnoreCase)) { Request.UserAgent = entry.Value; } else { Request.Headers[entry.Key] = entry.Value; } } } // Encode outbound data if (!string.IsNullOrEmpty(OutboundBody)) { byte[] data = Util.UTF8.GetBytes(OutboundBody); if (data.Length < 4096) { Request.ServicePoint.Expect100Continue = false; } Request.ContentLength = data.Length; using (Stream bstream = Request.GetRequestStream()) bstream.Write(data, 0, data.Length); } try { IAsyncResult result = Request.BeginGetResponse(ResponseCallback, null); ThreadPool.RegisterWaitForSingleObject( result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), null, HttpTimeout, true); } catch (WebException e) { if (e.Status != WebExceptionStatus.ProtocolError) { throw; } HttpWebResponse response = (HttpWebResponse)e.Response; Status = (int)response.StatusCode; ResponseBody = response.StatusDescription; _finished = true; } } catch (Exception e) { // m_log.Debug( // string.Format("[SCRIPTS HTTP REQUESTS]: Exception on request to {0} for {1} ", Url, ItemID), e); Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = e.Message; _finished = true; } }
public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); WebException wex = _savedResponseException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); }
public void All() { ServicePoint p = ServicePointManager.FindServicePoint(new Uri("mailto:[email protected]")); //WriteServicePoint ("A servicepoint that isn't really", p); ServicePointManager.MaxServicePoints = 2; ServicePoint google = ServicePointManager.FindServicePoint(new Uri("http://www.google.com")); try { ServicePoint slashdot = ServicePointManager.FindServicePoint(new Uri("http://www.slashdot.org")); Assert.Fail("#1"); } catch (InvalidOperationException) { } ServicePointManager.MaxServicePoints = 0; //WriteServicePoint ("google before getting a webrequest", google); HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.google.com"); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); #if FOUND_SOME_OTHER_URL // URL is no longer found, disabled the test until a more reliable URL is found :P //WriteServicePoint ("google after getting a response", google); ServicePoint google2 = ServicePointManager.FindServicePoint(new Uri("http://www.google.com/dilbert.html")); Assert.AreEqual(google, google2, "#equals"); res.Close(); #endif // in both instances property CurrentConnections is 0 according to ms.net. // let's see what it says when we do async operations... HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://www.google.com"); req2.Method = "PUT"; IAsyncResult async = req2.BeginGetRequestStream(null, null); //WriteServicePoint ("after async BeginGetRequestStream", google); // CurrentConnections: 1 Stream stream2 = req2.EndGetRequestStream(async); //WriteServicePoint ("after async EndGetRequestStream", google); // CurrentConnections: 1 stream2.Close(); req2 = (HttpWebRequest)WebRequest.Create("http://www.google.com"); async = req2.BeginGetResponse(null, null); //WriteServicePoint ("after async BeginGetResponse", google); // CurrentConnections: 2 WebResponse res2 = req2.EndGetResponse(async); //WriteServicePoint ("after async EndGetResponse", google); // CurrentConnections: 0 // curious that after you get the webresponse object CurrentConnections is set to 0. // you'd think that you'd still be connected until you close the webresponse.. //Console.WriteLine ("ContentLength: " + res2.ContentLength); res2.Close(); ServicePoint sp2; #if FOUND_SOME_OTHER_URL // unless of course some buffering is taking place.. let's check Uri uri2 = new Uri("http://freedesktop.org/Software/pkgconfig/releases/pkgconfig-0.15.0.tar.gz"); sp2 = ServicePointManager.FindServicePoint(uri2); req2 = (HttpWebRequest)WebRequest.Create(uri2); async = req2.BeginGetResponse(null, null); //WriteServicePoint ("Large file: after async BeginGetResponse", sp2); // CurrentConnections: 1 res2 = req2.EndGetResponse(async); //WriteServicePoint ("Large file: after async EndGetResponse", sp2); // CurrentConnections: 1 // and so it shows //Console.WriteLine ("ContentLength: " + res2.ContentLength); res2.Close(); #endif // what's the limit of the cache? req2 = (HttpWebRequest)WebRequest.Create("http://www.apache.org/"); res2 = req2.GetResponse(); sp2 = ServicePointManager.FindServicePoint(new Uri("http://www.apache.org/")); //WriteServicePoint ("apache", sp2); //Console.WriteLine ("ContentLength: " + res2.ContentLength); // CurrentConnections: 1 res2.Close(); // curious other effect: address is actually the full Uri of the previous request // anyways, buffer is probably 4096 bytes }
private void RequestStreamCallback(IAsyncResult ar) { HttpWebRequest request = (HttpWebRequest)ar.AsyncState; string boundary = "----pluploadboundary" + DateTime.Now.Ticks, dashdash = "--", crlf = "\r\n"; Stream requestStream = null; byte[] buffer = new byte[1048576], strBuff; int bytes; long loaded = 0, end = 0; int percent, lastPercent = 0; try { requestStream = request.EndGetRequestStream(ar); if (this.multipart) { request.ContentType = "multipart/form-data; boundary=" + boundary; // Add name to multipart array this.multipartParams["name"] = this.targetName; // Add chunking when needed if (this.chunking) { this.multipartParams["chunk"] = this.chunk; this.multipartParams["chunks"] = this.chunks; } // Append mutlipart parameters foreach (KeyValuePair <string, object> pair in this.multipartParams) { strBuff = this.StrToByteArray(dashdash + boundary + crlf + "Content-Disposition: form-data; name=\"" + pair.Key + '"' + crlf + crlf + pair.Value + crlf ); requestStream.Write(strBuff, 0, strBuff.Length); } // Append multipart file header strBuff = this.StrToByteArray( dashdash + boundary + crlf + "Content-Disposition: form-data; name=\"" + this.fileDataName + "\"; filename=\"" + this.name + '"' + crlf + "Content-Type: " + this.mimeType + crlf + crlf ); requestStream.Write(strBuff, 0, strBuff.Length); } else { request.ContentType = "application/octet-stream"; } // Move to start loaded = this.chunk * this.chunkSize; // Find end end = (this.chunk + 1) * this.chunkSize; if (end > this.Size) { end = this.Size; } while (loaded < end && (bytes = ReadByteRange(buffer, loaded, 0, (int)(end - loaded < buffer.Length ? end - loaded : buffer.Length))) != 0) { loaded += bytes; percent = (int)Math.Round((double)loaded / (double)this.Size * 100.0); if (percent > lastPercent) { syncContext.Post(delegate { if (percent > lastPercent) { this.OnProgress(new ProgressEventArgs(loaded, this.Size)); lastPercent = percent; } }, this); } requestStream.Write(buffer, 0, bytes); requestStream.Flush(); } // Append multipart file footer if (this.multipart) { strBuff = this.StrToByteArray(crlf + dashdash + boundary + dashdash + crlf); requestStream.Write(strBuff, 0, strBuff.Length); } } catch (Exception ex) { syncContext.Send(delegate { this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks)); }, this); } finally { try { if (requestStream != null) { requestStream.Close(); requestStream.Dispose(); requestStream = null; } } catch (Exception ex) { syncContext.Send(delegate { this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks)); }, this); } } try { request.BeginGetResponse(new AsyncCallback(ResponseCallback), request); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.RequestCanceled) { syncContext.Send(delegate { this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks)); }, this); } } catch (Exception ex) { syncContext.Send(delegate { this.OnIOError(new ErrorEventArgs(ex.Message, this.chunk, this.chunks)); }, this); } }
public static Action DownloadAsync(string url, string auth, string referer, string connectionGroupName, DateTime?cacheLastModifiedTime, Action <HttpWebResponse> onResponse, Action <byte[], int> onDownloadChunk, Action onComplete, Action <Exception> onException) { const int readBufferSize = 8192; const int requestTimeoutMS = 60000; const int readTimeoutMS = 60000; object sync = new object(); bool aborting = false; HttpWebRequest request = null; HttpWebResponse response = null; Stream responseStream = null; Action cleanup = () => { if (request != null) { request.Abort(); request = null; } if (responseStream != null) { try { responseStream.Close(); } catch { } responseStream = null; } if (response != null) { try { response.Close(); } catch { } response = null; } }; Action <Exception> abortDownloadInternal = (ex) => { lock (sync) { if (aborting) { return; } aborting = true; cleanup(); onException(ex); } }; Action abortDownload = () => { ThreadPool.QueueUserWorkItem((s) => { abortDownloadInternal(new Exception("Download has been aborted.")); }); }; lock (sync) { try { request = BuildWebRequest(url: url, auth: auth, connectionGroupName: connectionGroupName, cacheLastModifiedTime: cacheLastModifiedTime, referer: referer); // Unfortunately BeginGetResponse blocks until the DNS lookup has finished IAsyncResult requestResult = request.BeginGetResponse((requestResultParam) => { lock (sync) { try { if (aborting) { return; } response = (HttpWebResponse)request.EndGetResponse(requestResultParam); if (GetMIMETypeFromContentType(response.ContentType) == "text/html") { var memoryStream = new MemoryStream(); CopyStream(new ThrottledStream(response.GetResponseStream(), Settings.MaximumBytesPerSecond ?? ThrottledStream.Infinite), memoryStream); memoryStream.Position = 0; byte[] redirectPageBytes = memoryStream.ToArray(); Encoding pageEncoding = DetectHTMLEncoding(redirectPageBytes, response.ContentType); string metaRedirectHtml = pageEncoding.GetString(redirectPageBytes); memoryStream.Position = 0; responseStream = memoryStream; string redirectUrl = GetRedirectUrl(metaRedirectHtml, response.ResponseUri.AbsoluteUri); if (!string.IsNullOrEmpty(redirectUrl)) { HttpWebRequest redirectionRequest = BuildWebRequest(url: redirectUrl, auth: auth, connectionGroupName: connectionGroupName, cacheLastModifiedTime: cacheLastModifiedTime); response = (HttpWebResponse)redirectionRequest.GetResponse(); responseStream = new ThrottledStream(response.GetResponseStream(), Settings.MaximumBytesPerSecond ?? ThrottledStream.Infinite); } } else { responseStream = new ThrottledStream(response.GetResponseStream(), Settings.MaximumBytesPerSecond ?? ThrottledStream.Infinite); } onResponse(response); byte[] buff = new byte[readBufferSize]; AsyncCallback readCallback = null; readCallback = (readResultParam) => { lock (sync) { try { if (aborting) { return; } if (readResultParam != null) { int bytesRead = responseStream.EndRead(readResultParam); if (bytesRead == 0) { request = null; onComplete(); aborting = true; cleanup(); return; } onDownloadChunk(buff, bytesRead); } IAsyncResult readResult = responseStream.BeginRead(buff, 0, buff.Length, readCallback, null); ThreadPool.RegisterWaitForSingleObject(readResult.AsyncWaitHandle, (state, timedOut) => { if (!timedOut) { return; } abortDownloadInternal(new Exception("Timed out while reading response.")); }, null, readTimeoutMS, true); } catch (Exception ex) { abortDownloadInternal(ex); } } }; readCallback(null); } catch (Exception ex) { if (ex is WebException) { WebException webEx = (WebException)ex; if (webEx.Status == WebExceptionStatus.ProtocolError) { HttpStatusCode code = ((HttpWebResponse)webEx.Response).StatusCode; if (code == HttpStatusCode.NotFound) { ex = new HTTP404Exception(); } else if (code == HttpStatusCode.NotModified) { ex = new HTTP304Exception(); } } } abortDownloadInternal(ex); } } }, null); ThreadPool.RegisterWaitForSingleObject(requestResult.AsyncWaitHandle, (state, timedOut) => { if (!timedOut) { return; } abortDownloadInternal(new Exception("Timed out while waiting for response.")); }, null, requestTimeoutMS, true); } catch (Exception ex) { abortDownloadInternal(ex); } } return(abortDownload); }
public static IAsyncResult BeginGetCompressedResponse(this HttpWebRequest request, AsyncCallback callback, object state) { AddAcceptEncodingHeader(request); return(request.BeginGetResponse(callback, state)); }
/// <summary> /// Async Download base function /// </summary> protected void DownloadAsync() { asyncInProgress = true; timedOut = false; Log.Write(Log.Levels.Debug, "Starting async download for " + this.Url); Debug.Assert(Url.StartsWith("http")); DownloadStartTime = DateTime.Now; try { // If a registered progress-callback, inform it of our download progress so far. OnProgressCallback(0, 1); OnDebugCallback(this); BuildContentStream(); request = BuildRequest(); request.Timeout = 10000; readBuffer = new byte[1500]; IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(AsyncResponseCallback), this); // this line implements the timeout, if there is a timeout, the callback fires ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, request.Timeout, true); } catch (System.Configuration.ConfigurationException) { // is thrown by WebRequest.Create if App.config is not in the correct format // TODO: don't know what to do with it throw; } catch (WebException e) { // Abort() was called. Utility.Log.Write(Log.Levels.Debug, "NET", "DownloadAsync(): WebException: " + e.Status.ToString()); SaveException(e); // Cancel(); AsyncFinishDownload(); } catch (System.IO.IOException e) { //SaveException(new Exception("Request actually processing... This Request will be Canceled")); Utility.Log.Write(Log.Levels.Debug, "NET", "DownloadAsync(): IOException: " + e.Message.ToString()); Cancel(); } catch (NullReferenceException e) { Utility.Log.Write(Log.Levels.Debug, "NET", "DownloadAsync(): NullReferenceException: " + e.Message); SaveException(e); AsyncFinishDownload(); } catch (Exception e) { Utility.Log.Write(Log.Levels.Debug, "NET", "DownloadAsync(): Exception: " + e.Message); SaveException(e); //Cancel(); AsyncFinishDownload(); } }
/// <summary> /// A blocking operation that does not continue until a response has been /// received for a given <see cref="HttpWebRequest"/>, or the request /// timed out. /// </summary> /// <param name="request">The request to be sent.</param> /// <param name="timeout">An optional timeout.</param> /// <returns>The response that was received for the request.</returns> /// <exception cref="TimeoutException">If the <paramref name="timeout"/> /// parameter was set, and no response was received within the specified /// time.</exception> /// <remarks> /// This particular extension method (GetSyncResponse) was originally developed by Philipp Sumi under MS-PL with permission /// to convert to Apache <see href="http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight"/> /// (URL content as of 25-May-2015 11:28am GMT+2) /// /// Now converted to AGPL from Apache Licensed RestSharp <see href="https://github.com/restsharp/RestSharp" /> /// The invalidity or unenforceability of this license conversion for this block of code within method: GetSyncResponse /// shall not affect the validity or enforceability of the applied license on the rest of the code in this software /// which shall remain in full force and effect. /// </remarks> public static HttpWebResponse GetSyncResponse(this HttpWebRequest request, int?timeout) { if (request == null) { throw new ArgumentNullException("request"); } var waitHandle = new AutoResetEvent(false); HttpWebResponse response = null; Exception exception = null; AsyncCallback callback = ar => { try { //get the response response = (HttpWebResponse)request.EndGetResponse(ar); } catch (WebException we) { if (we.Status != WebExceptionStatus.RequestCanceled) { exception = we; } } catch (Exception e) { exception = e; } finally { //setting the handle unblocks the loop below waitHandle.Set(); } }; //request response async var asyncResult = request.BeginGetResponse(callback, null); if (asyncResult.CompletedSynchronously) { return(response); } var hasSignal = waitHandle.WaitOne(timeout ?? Timeout.Infinite); if (!hasSignal) { try { if (response != null) { return(response); } if (request != null) { request.Abort(); } } catch { throw new TimeoutException("No response received in time."); } throw new TimeoutException("No response received in time."); } //bubble exception that occurred on worker thread if (exception != null) { throw exception; } return(response); }
private async void handleRequest(StreamSocket socket) { Logger.log("XHRProxy", "Received incoming HTTP request"); DataWriter writer = new DataWriter(socket.OutputStream); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; // deny any request that isn't from localhost if (socket.Information.RemoteAddress.RawName != "::1") { Logger.log("XHRProxy", "403 Forbidden; remote address \"" + socket.Information.RemoteAddress.RawName + "\" != \"::1\""); requestError(writer, socket, "403 Forbidden", "Forbidden"); return; } DataReader reader = new DataReader(socket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; RequestParseState state = RequestParseState.GetRequest; string urlPrefix = "/fetch/" + this.securityToken + "/"; UInt32 numBytesRead = 0; UInt32 requestBufferSize = 4096; string buffer = ""; string httpMethod = ""; string url = ""; bool isLocalFile = true; Uri httpUri = null; int p, q; bool needMoreData = true; HttpWebRequest request = null; Dictionary <string, string> headers = new Dictionary <string, string>(); int responseBufferSize = 4096; int responseBytesRead = 0; int responseTotalBytesRead = 0; byte[] responseBuffer = new byte[responseBufferSize]; try { while (true) { Logger.log("XHRProxy", "State = " + states[(int)state]); if (needMoreData) { numBytesRead = await reader.LoadAsync(requestBufferSize); Logger.log("XHRProxy", "Read " + numBytesRead + " bytes"); buffer += reader.ReadString(numBytesRead); } switch (state) { case RequestParseState.GetRequest: // go until first \n p = buffer.IndexOf("\r\n"); if (p != -1) { // parse out the request string[] tokens = buffer.Substring(0, p).Split(' '); if (tokens.Length != 3) { Logger.log("XHRProxy", "400 Bad Request; request had " + tokens.Length + " tokens, expected 3"); requestError(writer, socket, "400 Bad Request", "Bad Request"); return; } httpMethod = tokens[0].ToUpper(); Logger.log("XHRProxy", "Method = " + httpMethod); url = tokens[1]; q = url.IndexOf(urlPrefix); if (q != 0) { Logger.log("XHRProxy", "400 Bad Request"); requestError(writer, socket, "400 Bad Request", "Bad Request"); return; } string encodedUrl = url.Substring(q + urlPrefix.Length); string decodedUrl = HttpUtility.UrlDecode(encodedUrl).Replace(' ', '+'); byte[] data = Convert.FromBase64String(decodedUrl); url = Encoding.UTF8.GetString(data, 0, data.Length); if (url.IndexOf("http://") == 0 || url.IndexOf("https://") == 0) { isLocalFile = false; } Logger.log("XHRProxy", "URL = " + url); buffer = buffer.Substring(p + 2); needMoreData = false; state = RequestParseState.Headers; } else if (numBytesRead < requestBufferSize) { // not enough data, bad request Logger.log("XHRProxy", "400 Bad Request; not enough data"); requestError(writer, socket, "400 Bad Request", "Bad Request"); return; } else { // need more data Logger.log("XHRProxy", "Need more data..."); needMoreData = true; } break; case RequestParseState.Headers: p = buffer.IndexOf("\r\n\r\n"); // two line breaks if (p != -1) { Logger.log("XHRProxy", "Original HTTP Request Headers:"); string[] lines = buffer.Substring(0, p).Split('\n'); foreach (string line in lines) { q = line.IndexOf(':'); if (q != -1) { string name = line.Substring(0, q); string value = line.Substring(q + 2).Trim(); Logger.log("XHRProxy", " " + name + ": " + value); headers[name] = value; } else { Logger.log("XHRProxy", " Bad HTTP header \"" + line + "\", ignoring"); } } buffer = buffer.Substring(p + 4); state = isLocalFile ? RequestParseState.ServeFile : RequestParseState.CreateRequest; } else if (numBytesRead < requestBufferSize) { // not enough data, bad request Logger.log("XHRProxy", "400 Bad Request; not enough data"); requestError(writer, socket, "400 Bad Request", "Bad Request"); return; } else { // need more data Logger.log("XHRProxy", "Need more data..."); needMoreData = true; } if (state == RequestParseState.ServeFile) { continue; } break; case RequestParseState.ServeFile: string originalFile = url; string file = collapsePath(originalFile); if (file.IndexOf("..") == 0) { Logger.log("XHRProxy", "400 Bad Request"); Logger.log("XHRProxy", "Original file: " + originalFile); Logger.log("XHRProxy", "Resolved file: " + file); requestError(writer, socket, "400 Bad Request", "The requested file must not begin with \"..\""); return; } file = file.Replace('/', '\\'); if (file.StartsWith("\\")) { file = "App" + file; } else { file = "App\\" + file; } StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFile theFile; try { theFile = await installFolder.GetFileAsync(file); } catch (Exception) { Logger.log("XHRProxy", "404 File Not Found"); Logger.log("XHRProxy", "Original file: " + originalFile); Logger.log("XHRProxy", "Resolved file: " + file); requestError(writer, socket, "404 File Not Found", "File Not Found"); return; } var randomAccessStream = await theFile.OpenReadAsync(); Stream fs = randomAccessStream.AsStreamForRead(); FileInfo fi = new FileInfo(file); string ext = fi.Extension.Substring(1); // trim the dot string mimetype = "application/octet-stream"; if (mimeTypes.ContainsKey(ext)) { mimetype = mimeTypes[ext]; } Logger.log("XHRProxy", "Status: 200 OK"); Logger.log("XHRProxy", "Actual HTTP headers being returned:"); Logger.log("XHRProxy", " Content-Type: " + mimetype); Logger.log("XHRProxy", " Content-Length: " + fi.Length); Logger.log("XHRProxy", " Connection: close"); writer.WriteString("HTTP/1.0 200 OK\r\n"); writer.WriteString("Content-Type: " + mimetype + "\r\n"); writer.WriteString("Content-Length: " + fi.Length + "\r\n"); writer.WriteString("Connection: close\r\n\r\n"); while ((responseBytesRead = fs.Read(responseBuffer, 0, responseBuffer.Length)) > 0) { responseTotalBytesRead += responseBytesRead; writer.WriteBytes(responseBuffer); } Logger.log("XHRProxy", "Returned " + responseTotalBytesRead + " bytes"); await writer.StoreAsync(); socket.Dispose(); return; case RequestParseState.CreateRequest: httpUri = new Uri(url, UriKind.Absolute); request = (HttpWebRequest)WebRequest.CreateHttp(httpUri); request.Method = httpMethod; Logger.log("XHRProxy", "Actual HTTP headers being sent:"); foreach (string key in headers.Keys) { if (key == "Accept") { Logger.log("XHRProxy", " Accept: " + headers[key]); request.Accept = headers[key]; } else if (key == "Content-Type") { if (httpMethod == "POST" || httpMethod == "PUT") { Logger.log("XHRProxy", " Content-Type: " + headers[key]); request.ContentType = headers[key]; } } else if (key == "Host") { Logger.log("XHRProxy", " Host: " + httpUri.Host); request.Headers["Host"] = httpUri.Host; } else { Logger.log("XHRProxy", " " + key + ": " + headers[key]); request.Headers[key] = headers[key]; } } if (httpMethod == "POST" || httpMethod == "PUT") { Stream requestStream = await Task.Factory.FromAsync <Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null); byte[] jsonAsBytes = Encoding.UTF8.GetBytes(buffer); Logger.log("XHRProxy", "Body:"); Logger.log("XHRProxy", buffer); await requestStream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length); if (numBytesRead == requestBufferSize) { // pump the rest of the data while (true) { numBytesRead = await reader.LoadAsync(requestBufferSize); if (numBytesRead == 0) { break; } Logger.log("XHRProxy", "Read " + numBytesRead + " bytes"); buffer = reader.ReadString(numBytesRead); Logger.log("XHRProxy", buffer); byte[] jsonAsBytes2 = Encoding.UTF8.GetBytes(buffer); await requestStream.WriteAsync(jsonAsBytes2, 0, jsonAsBytes2.Length); if (numBytesRead < requestBufferSize) { break; } } } requestStream.Close(); } Logger.log("XHRProxy", "Sending request..."); request.BeginGetResponse(async callbackResult => { try { Logger.log("XHRProxy", "Reading response..."); HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult); Logger.log("XHRProxy", "Status: " + (int)response.StatusCode + " " + response.StatusDescription); writer.WriteString("HTTP/1.0 " + (int)response.StatusCode + " " + response.StatusDescription + "\r\n"); Logger.log("XHRProxy", "Original HTTP response headers:"); foreach (string key in response.Headers.AllKeys) { Logger.log("XHRProxy", " " + key + ": " + response.Headers[key]); } Logger.log("XHRProxy", "Actual HTTP headers being returned:"); foreach (string key in response.Headers.AllKeys) { if (key == "Connection") { Logger.log("XHRProxy", " Connection: close"); writer.WriteString("Connection: close\r\n"); } else { Logger.log("XHRProxy", " " + key + ": " + response.Headers[key]); writer.WriteString(key + ": " + response.Headers[key] + "\r\n"); } } writer.WriteString("\r\n"); Stream responseStream = response.GetResponseStream(); BinaryReader br = new BinaryReader(responseStream); byte[] responseBytes = br.ReadBytes(4096); while (responseBytes.Length > 0) { responseTotalBytesRead += responseBytes.Length; writer.WriteBytes(responseBytes); responseBytes = br.ReadBytes(4096); } Logger.log("XHRProxy", "Returned " + responseTotalBytesRead + " bytes"); await writer.StoreAsync(); socket.Dispose(); } catch (WebException ex) { // check if we have an expired or self-signed cert if (ex.Status == WebExceptionStatus.UnknownError) { if (ex.Response.Headers.Count == 0 && httpUri.Scheme == "https") { Logger.log("XHRProxy", "Invalid SSL certificate, returning a 400 Bad Request"); requestError(writer, socket, "400 Bad Request", "Invalid SSL certificate"); } else { Logger.log("XHRProxy", "File not found, returning a 404"); requestError(writer, socket, "404 File Not Found", "File Not Found"); } } else { Logger.log("XHRProxy", "400 Bad Request"); Logger.log("XHRProxy", ex.Status.ToString()); requestError(writer, socket, "400 Bad Request", ex.Status.ToString()); } return; } }, null); return; } } } catch (Exception ex) { Logger.log("XHRProxy", "500 Internal Server Error"); foreach (string s in ex.ToString().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)) { Logger.log("XHRProxy", s); } requestError(writer, socket, "500 Internal Server Error", ex.Message); } }
/// <summary> /// Perform the WebDAV call and fire the callback when finished. /// </summary> /// <param name="uri"></param> /// <param name="requestMethod"></param> /// <param name="headers"></param> /// <param name="content"></param> /// <param name="uploadFilePath"></param> /// <param name="callback"></param> /// <param name="state"></param> void HTTPRequest(Uri uri, string requestMethod, IDictionary <string, string> headers, byte[] content, string uploadFilePath, AsyncCallback callback, object state) { httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri); /* * The following line fixes an authentication problem explained here: * http://www.devnewsgroups.net/dotnetframework/t9525-http-protocol-violation-long.aspx */ System.Net.ServicePointManager.Expect100Continue = false; // If you want to disable SSL certificate validation /* * System.Net.ServicePointManager.ServerCertificateValidationCallback += * delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslError) * { * bool validationResult = true; * return validationResult; * }; */ // The server may use authentication if (user != null && pass != null) { NetworkCredential networkCredential; if (domain != null) { networkCredential = new NetworkCredential(user, pass, domain); } else { networkCredential = new NetworkCredential(user, pass); } httpWebRequest.Credentials = networkCredential; // Send authentication along with first request. httpWebRequest.PreAuthenticate = true; } httpWebRequest.Method = requestMethod; // Need to send along headers? if (headers != null) { foreach (string key in headers.Keys) { httpWebRequest.Headers.Set(key, headers[key]); } } // Need to send along content? if (content != null || uploadFilePath != null) { RequestState asyncState = new RequestState(); asyncState.request = httpWebRequest; asyncState.userCallback = callback; asyncState.userState = state; if (content != null) { // The request either contains actual content... httpWebRequest.ContentLength = content.Length; asyncState.content = content; httpWebRequest.ContentType = "text/xml"; } else { // ...or a reference to the file to be added as content. httpWebRequest.ContentLength = new FileInfo(uploadFilePath).Length; asyncState.uploadFilePath = uploadFilePath; } // Perform asynchronous request. IAsyncResult r = (IAsyncResult)asyncState.request.BeginGetRequestStream(new AsyncCallback(ReadCallback), asyncState); } else { // Begin async communications httpWebRequest.BeginGetResponse(callback, state); } }
private static void WorkerThreadProc(object unused) { Random random = new Random(); List <ImageViewerLowProfileImageLoader.PendingRequest> pendingRequestList = new List <ImageViewerLowProfileImageLoader.PendingRequest>(); Queue <IAsyncResult> asyncResultQueue = new Queue <IAsyncResult>(); while (!ImageViewerLowProfileImageLoader._exiting) { lock (ImageViewerLowProfileImageLoader._syncBlock) { if (ImageViewerLowProfileImageLoader._pendingRequests.Count == 0 && ImageViewerLowProfileImageLoader._pendingResponses.Count == 0 && (pendingRequestList.Count == 0 && asyncResultQueue.Count == 0)) { Monitor.Wait(ImageViewerLowProfileImageLoader._syncBlock); if (ImageViewerLowProfileImageLoader._exiting) { break; } } while (0 < ImageViewerLowProfileImageLoader._pendingRequests.Count) { ImageViewerLowProfileImageLoader.PendingRequest local_7 = ImageViewerLowProfileImageLoader._pendingRequests.Dequeue(); for (int local_8 = 0; local_8 < pendingRequestList.Count; ++local_8) { if (pendingRequestList[local_8].Image == local_7.Image) { pendingRequestList[local_8] = local_7; local_7 = (ImageViewerLowProfileImageLoader.PendingRequest)null; break; } } if (local_7 != null) { pendingRequestList.Add(local_7); } } while (0 < ImageViewerLowProfileImageLoader._pendingResponses.Count) { asyncResultQueue.Enqueue(ImageViewerLowProfileImageLoader._pendingResponses.Dequeue()); } } Queue <ImageViewerLowProfileImageLoader.PendingCompletion> pendingCompletions = new Queue <ImageViewerLowProfileImageLoader.PendingCompletion>(); int count = pendingRequestList.Count; for (int index1 = 0; 0 < count && index1 < 5; ++index1) { int index2 = random.Next(count); ImageViewerLowProfileImageLoader.PendingRequest pendingRequest = pendingRequestList[index2]; pendingRequestList[index2] = pendingRequestList[count - 1]; pendingRequestList.RemoveAt(count - 1); --count; HttpWebRequest http = WebRequest.CreateHttp(pendingRequest.Uri); http.AllowReadStreamBuffering = true; http.BeginGetResponse(new AsyncCallback(ImageViewerLowProfileImageLoader.HandleGetResponseResult), (object)new ImageViewerLowProfileImageLoader.ResponseState((WebRequest)http, pendingRequest.Image, pendingRequest.Uri, pendingRequest.Timestamp)); Thread.Sleep(1); } for (int index = 0; 0 < asyncResultQueue.Count && index < 5; ++index) { IAsyncResult asyncResult = asyncResultQueue.Dequeue(); ImageViewerLowProfileImageLoader.ResponseState responseState = (ImageViewerLowProfileImageLoader.ResponseState)asyncResult.AsyncState; try { WebResponse response = responseState.WebRequest.EndGetResponse(asyncResult); pendingCompletions.Enqueue(new ImageViewerLowProfileImageLoader.PendingCompletion(responseState.Image, responseState.Uri, response.GetResponseStream(), responseState.Timestamp)); } catch (WebException ex) { Logger.Instance.Error(string.Format("LowProfileImageLoader exception when fetching {0}", (object)responseState.Uri.OriginalString), (Exception)ex); } Thread.Sleep(1); } if (0 < pendingCompletions.Count) { Deployment.Current.Dispatcher.BeginInvoke((Action)(() => { while (0 < pendingCompletions.Count) { ImageViewerLowProfileImageLoader.PendingCompletion pendingCompletion = pendingCompletions.Dequeue(); if (ImageViewerLowProfileImageLoader.GetUriSource(pendingCompletion.Image) == pendingCompletion.Uri) { BitmapImage bitmapImage; if (pendingCompletion.Image.Source == null) { bitmapImage = new BitmapImage() { CreateOptions = BitmapCreateOptions.BackgroundCreation } } ; else { bitmapImage = new BitmapImage(); } try { bitmapImage.SetSource(pendingCompletion.Stream); } catch (Exception ex) { Logger.Instance.Error("Error of reading image", ex); } pendingCompletion.Image.Source = (ImageSource)bitmapImage; DateTime now = DateTime.Now; if (ImageViewerLowProfileImageLoader.ImageDownloaded != null) { ImageViewerLowProfileImageLoader.ImageDownloaded(null, new EventArgs()); } ImageViewerLowProfileImageLoader.Log(string.Format("Downloaded image {0} in {1} ms.", (object)pendingCompletion.Uri.OriginalString, (object)(now - pendingCompletion.Timestamp).TotalMilliseconds)); } pendingCompletion.Stream.Dispose(); } })); } } }
/// <summary> /// Read file from Isolated Storage and sends it to server /// </summary> /// <param name="asynchronousResult"></param> private void uploadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest webRequest = reqState.request; string callbackId = reqState.options.CallbackId; try { using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult))) { string lineStart = "--"; string lineEnd = Environment.NewLine; byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd; if (!string.IsNullOrEmpty(reqState.options.Params)) { Dictionary <string, string> paramMap = parseHeaders(reqState.options.Params); foreach (string key in paramMap.Keys) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string formItem = string.Format(formdataTemplate, key, paramMap[key]); byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem); requestStream.Write(formItemBytes, 0, formItemBytes.Length); } requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(reqState.options.FilePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0))); return; } byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd); long totalBytesToSend = 0; using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile)) { string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd; string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType); byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header); byte[] buffer = new byte[4096]; int bytesRead = 0; totalBytesToSend = fileStream.Length; requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); requestStream.Write(headerBytes, 0, headerBytes.Length); while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { if (!reqState.isCancelled) { requestStream.Write(buffer, 0, bytesRead); bytesSent += bytesRead; DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId); System.Threading.Thread.Sleep(1); } else { throw new Exception("UploadCancelledException"); } } } requestStream.Write(endRequest, 0, endRequest.Length); } } // webRequest webRequest.BeginGetResponse(ReadCallback, reqState); } catch (Exception ex) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } } }
private void TestWebServiceConnection(string url, int timeoutMilliseconds) { request = (HttpWebRequest)WebRequest.Create(url); request.BeginGetResponse(new AsyncCallback(FinishWebRequest), null); timer = new System.Threading.Timer(new TimerCallback(abortRequest), null, timeoutMilliseconds, Timeout.Infinite); }
/// <summary> /// Метод заполняет коллекцию заданных сущностей в модели представления, /// оправляя асинхронный GET-запрос к REST-сервису. /// </summary> /// <typeparam name="T"> /// По типу сущности определяется, какой необходимо отправить запрос к REST-сервису, /// а также определяется, какая модель представления участвует в процессе. /// </typeparam> /// <param name="id">Идентификатор извлекаемой сущности, опциональный</param> public void SelectAsync <T>(int?id = null) { var serializer = new DataContractJsonSerializer(typeof(T[])); string entityName = typeof(T).Name; HttpWebRequest httpWebRequest = WebRequest.CreateHttp(RestServiceAddress + entityName + (id.HasValue ? "/" + id : string.Empty)); httpWebRequest.Method = "GET"; var r = httpWebRequest.BeginGetResponse(asyncResult => { var request = (HttpWebRequest)asyncResult.AsyncState; var response = (HttpWebResponse)request.EndGetResponse(asyncResult); try { var entityArray = (T[])serializer.ReadObject(response.GetResponseStream()); var entityObservableCollection = new ObservableCollection <T>(entityArray); if (typeof(T) == typeof(Order)) { var entityViewModel = new OrderViewModel() { Orders = entityObservableCollection as ObservableCollection <Order> }; } else if (typeof(T) == typeof(Product)) { var entityViewModel = new ProductViewModel() { Products = entityObservableCollection as ObservableCollection <Product> }; } else if (typeof(T) == typeof(ProductDescriptor)) { var entityViewModel = new ProductDescriptorViewModel() { ProductDescriptors = entityObservableCollection as ObservableCollection <ProductDescriptor> }; } } catch (Exception) { if (typeof(T) == typeof(Order)) { var entityViewModel = new OrderViewModel() { Orders = null }; } else if (typeof(T) == typeof(Product)) { var entityViewModel = new ProductViewModel() { Products = null }; } else if (typeof(T) == typeof(ProductDescriptor)) { var entityViewModel = new ProductDescriptorViewModel() { ProductDescriptors = null }; } } RaisePropertyChanged("SelectAsyncCompleted"); }, httpWebRequest); }
private async void UpoadFile(string parameters) { if (uploading) { string js = "var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.file.upload.busy',true,true);" + "e.success=false;e.message='busy';document.dispatchEvent(e);"; InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); return; } string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize <string[]>(parameters); string localURL = args[0]; string uploadURL = args[1]; string folderName = args[2]; string mimeType = args[3]; string uploadProgressCallback = args[4]; if (localURL == null || localURL.Length == 0) { callJSwithError("Missing filename parameter."); return; } updateCallback = (uploadProgressCallback != null && uploadProgressCallback.Length > 0) ? uploadProgressCallback : null; fileUpload = localURL; uploading = true; FileStream file = System.IO.File.OpenRead(localURL); fileSize = file.Length; byte[] fileBytes = new byte[file.Length]; for (int i = 0; i < fileBytes.Length; i++) { fileBytes[i] = (byte)file.ReadByte(); } var Params = new Dictionary <string, string>(); string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(uploadURL)); httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest.Method = "POST"; httpWebRequest.BeginGetRequestStream((result) => { try { notifyBytesSent(0, fileSize); HttpWebRequest request = (HttpWebRequest)result.AsyncState; using (Stream requestStream = request.EndGetRequestStream(result)) { WriteMultipartForm(requestStream, boundary, Params, Path.GetFileName(localURL), mimeType, fileBytes, folderName); } request.BeginGetResponse(a => { try { var response = request.EndGetResponse(a); var responseStream = response.GetResponseStream(); using (var sr = new StreamReader(responseStream)) { using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { string responseString = streamReader.ReadToEnd(); uploading = false; notifyBytesSent(fileSize, fileSize); notifySuccess(); } } } catch (Exception ex) { uploading = false; callJSwithError(string.Format("Cannot upload the file '{0}' for upload!", localURL)); } }, null); } catch (Exception) { uploading = false; callJSwithError(string.Format("Cannot upload the file '{0}' for upload!", localURL)); } }, httpWebRequest); }
private void BeginRequest(HttpWebRequest request, System.Action<HttpResult> onResult) { //int total = 0; //byte[] buffer = new byte[1000]; request.BeginGetResponse(new AsyncCallback((result) => { var data = request.EndGetResponse(result); HttpResult r = new HttpResult(); try { var stream = new StreamReader(data.GetResponseStream()); r.response = stream.ReadToEnd(); stream.Close(); //TODO:!! /*stream.BeginRead(buffer, 0, 1000, new AsyncCallback((read) => { var r = stream.EndRead(read); if (r == 0) { //TODO: !! } else { //stream.BeginRead } }));*/ } catch (Exception ex) { r.errDescr = ex.Message; } finally { data.Close(); } if (onResult != null) { onResult(r); } }), null); }
public void download(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; downloadOptions.FilePath = optionStrings[1]; bool trustAll = false; bool.TryParse(optionStrings[2], out trustAll); downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[3]; downloadOptions.Headers = optionStrings[4]; downloadOptions.CallbackId = callbackId = optionStrings[5]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } //catch (WebException webEx) //{ //} catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } }
public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); Assert.Equal(1, _responseCallbackCallCount); }
private void GetVendorsAppbarBtn_Click(object sender, EventArgs e) { request = WebRequest.CreateHttp("http://localhost:9191/AdventureWorksRestJSON.svc/Vendors"); request.BeginGetResponse(new AsyncCallback(GetVendors), null); }
public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(null, null); _savedHttpWebRequest.Abort(); }
private static void MakeRequest(string ContentType, string Method, string URL, object Parameters, Action <string> SuccessCallback, Action <WebException> FailCallback) { if (Parameters == null) { throw new ArgumentNullException("Parameters object cannot be null"); } if (string.IsNullOrWhiteSpace(ContentType)) { throw new ArgumentException("Content type is missing"); } if (string.IsNullOrWhiteSpace(URL)) { throw new ArgumentException("URL is empty"); } if (Method != "HEAD" && Method != "GET" && Method != "POST" && Method != "DELETE" && Method != "PUT") { throw new ArgumentException("Invalid Method"); } try { /* * Create new Request */ HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URL)); request.CookieContainer = cookies; request.Method = Method; request.ContentType = ContentType; request.UserAgent = UserAgent; if (Proxy != null) { request.Proxy = Proxy; } /* * Asynchronously get the response */ if (Method == "POST" || Method == "PUT" || Method == "DELETE") { request.BeginGetRequestStream(new AsyncCallback((IAsyncResult callbackResult) => { HttpWebRequest tmprequest = (HttpWebRequest)callbackResult.AsyncState; Stream postStream; postStream = tmprequest.EndGetRequestStream(callbackResult); string postbody = ""; postbody = Utils.SerializeQueryString(Parameters); // Convert the string into a byte array. byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postbody); // Write to the request stream. postStream.Write(byteArray, 0, byteArray.Length); postStream.Flush(); postStream.Dispose(); // Start the asynchronous operation to get the response tmprequest.BeginGetResponse(ProcessCallback(SuccessCallback, FailCallback), tmprequest); }), request); } else if (Method == "GET" || Method == "HEAD") { request.BeginGetResponse(ProcessCallback(SuccessCallback, FailCallback), request); } } catch (WebException webEx) { FailCallback(webEx); } }