BeginGetResponse() public method

public BeginGetResponse ( AsyncCallback callback, object state ) : IAsyncResult
callback AsyncCallback
state object
return IAsyncResult
        public void Send()
        {
            HttpRequestState requestState = new HttpRequestState();

            requestState.Request = webRequest;

            if (requestBytes != null)
            {
                webRequest.BeginGetRequestStream(RequestStreamData, requestState);
            }
            else
            {
                webRequest.BeginGetResponse(ReceivedData, requestState);
            }
        }
Example #2
0
 private void GetRequest(string word)
 {
     Uri reqUri = GetRequestUri(word);
     request = (HttpWebRequest)WebRequest.Create(reqUri);
     AsyncCallback callback = new AsyncCallback(ProcessRequest);
     request.BeginGetResponse(callback, null);
 }
 private HttpWebResponse GetResponseAsynch(HttpWebRequest request)
 {
     return AsynchHelper.WaitForAsynchResponse(
         c => request.BeginGetResponse(c, null),
         (r, s) => (HttpWebResponse)request.EndGetResponse(r)
     );
 }
Example #4
0
    public void BeginGetHeight(XYPoint point, int UTMZone)
    {
      string url = String.Format("http://kmswww3.kms.dk/FindMinHoejde/Default.aspx?display=show&csIn=utm{2}_euref89&csOut=utm32_euref89&x={0}&y={1}&c=dk", point.X, point.Y, UTMZone);

      request = (HttpWebRequest)WebRequest.Create(url);
      result= (IAsyncResult) request.BeginGetResponse(new AsyncCallback(RespCallback),null);
    }
        public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
        {
            if (timeoutMs > 0)
            {
                return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
            }

            var tcs = new TaskCompletionSource<WebResponse>();

            try
            {
                request.BeginGetResponse(iar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(iar);
                        tcs.SetResult(response);
                    }
                    catch (Exception exc)
                    {
                        tcs.SetException(exc);
                    }
                }, null);
            }
            catch (Exception exc)
            {
                tcs.SetException(exc);
            }

            return tcs.Task;
        }
Example #6
0
        /// <summary>
        /// Encapsulates GetResponse so tests don't invoke the request
        /// </summary>
        /// <param name="req">Request to Twitter</param>
        /// <returns>Response to Twitter</returns>
        public static HttpWebResponse AsyncGetResponse(HttpWebRequest req)
        {
            Exception asyncException = null;

            var resetEvent = new ManualResetEvent(/*initialStateSignaled:*/ false);
            HttpWebResponse res = null;

            req.BeginGetResponse(
                new AsyncCallback(
                    ar =>
                    {
                        try
                        {
                            res = req.EndGetResponse(ar) as HttpWebResponse;
                        }
                        catch (Exception ex)
                        {
                            asyncException = ex;
                        }
                        finally
                        {
                            resetEvent.Set();
                        }
                    }), null);

            resetEvent.WaitOne();

            if (asyncException != null)
            {
                throw asyncException;
            }

            return res;
        }
 public void Download(String URL)
 {
     URL = HttpUtility.UrlEncode(URL);
     string req_src = api_req_url + URL;
     wr = (HttpWebRequest)HttpWebRequest.Create(new Uri(req_src, UriKind.Absolute));
     wr.BeginGetResponse(new AsyncCallback(req_callback), wr);
 }
Example #8
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            if (list.Items.Count != 0)
                list.Items.Clear();

            http = (HttpWebRequest)WebRequest.Create("http://192.168.2.39/TOSWEB/webservice/service.php");
            http.BeginGetResponse(new AsyncCallback(ReadWebRequestCallBack), http);
        }
Example #9
0
        public void FetchSearchResults(HttpWebRequest queryRequest)
        {
            this.WebResultCollection.Clear();

            IsLoading = true;

            queryRequest.BeginGetResponse(new AsyncCallback(ReadCallback), queryRequest);
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            DownloadStatusText.Text = "Downloading image from " + imageUrl;
            webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(imageUrl);
            webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), webRequest);

            base.OnNavigatedTo(e);
        }
Example #11
0
        public static IEnumerator<object> IssueRequest(HttpWebRequest request)
        {
            var fResponse = new Future<HttpWebResponse>();
            ThreadPool.QueueUserWorkItem(
                (__) => {
                    try {
                        request.BeginGetResponse(
                            (ar) => {
                                try {
                                    var _ = (HttpWebResponse)request.EndGetResponse(ar);
                                    fResponse.SetResult(_, null);
                                } catch (Exception ex) {
                                    fResponse.SetResult(null, ex);
                                }
                            }, null
                        );
                    } catch (Exception ex_) {
                        fResponse.SetResult(null, ex_);
                    }
                }
            );

            yield return fResponse;
            if (fResponse.Failed)
                throw new RequestFailedException(fResponse.Error);

            using (var response = fResponse.Result) {
                var fResponseStream = Future.RunInThread(
                    () => response.GetResponseStream()
                );
                yield return fResponseStream;

                Encoding encoding = AsyncTextReader.DefaultEncoding;
                if (!string.IsNullOrEmpty(response.CharacterSet))
                    encoding = Encoding.GetEncoding(response.CharacterSet);

                string responseText;
                using (var stream = fResponseStream.Result)
                using (var adapter = new AsyncTextReader(new StreamDataAdapter(stream, false), encoding)) {
                    var fText = adapter.ReadToEnd();

                    yield return fText;

                    responseText = fText.Result;
                }

                var cookies = new Cookie[response.Cookies.Count];
                response.Cookies.CopyTo(cookies, 0);

                yield return new Result(new Response {
                    Body = responseText,
                    ContentType = response.ContentType,
                    StatusCode = response.StatusCode,
                    StatusDescription = response.StatusDescription,
                    Cookies = cookies
                });
            }
        }
Example #12
0
        public void SendCommandAsync(JsonAsyncCallback jCallback)
        {
            jb = jCallback;
            //String qryString = uri + name + "?" + (secret != Guid.Empty ? ("secret=" + secret.ToString() + "&") : "") + paramString;
            String qryString = uri + name + "?" + paramString;

            request = (HttpWebRequest)HttpWebRequest.Create(qryString);
            IAsyncResult result = (IAsyncResult)request.BeginGetResponse(RespCallback, null);
        }
Example #13
0
 static void SendMinecraftNetBeat() {
     HeartbeatData data = new HeartbeatData( MinecraftNetUri );
     if( !RaiseHeartbeatSendingEvent( data, MinecraftNetUri, true ) ) {
         return;
     }
     minecraftNetRequest = CreateRequest( data.CreateUri() );
     var state = new HeartbeatRequestState( minecraftNetRequest, data );
     minecraftNetRequest.BeginGetResponse( ResponseCallback, state );
 }
Example #14
0
 public void GetData()
 {
     using (var File = IsolatedStorageFile.GetUserStoreForApplication())
     {
         request = (HttpWebRequest)HttpWebRequest.Create("http://www.search4rss.com/search.php?lang=en&q=" + txt_Search.Text);
         Dispatcher.BeginInvoke(() => RssList.Visibility=Visibility.Collapsed);
         Dispatcher.BeginInvoke(() => Loading_for_Search.Visibility=Visibility.Visible);
         request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
     }
 }
Example #15
0
 private System.Net.HttpWebResponse GetResponse(System.Net.HttpWebRequest req)
 {
     try {
         var responseAsyncResult = req.BeginGetResponse(null, null);
         var returnValue         = req.EndGetResponse(responseAsyncResult);
         return((System.Net.HttpWebResponse)returnValue);
     } catch (System.Net.WebException wex) {
         return((System.Net.HttpWebResponse)wex.Response);
     }
 }
 private void BeginRequest(string method, HttpWebRequest httpRequest, AsyncRequest rawRequestData)
 {
     if (method == "PUT" || method == "POST")
     {
         httpRequest.BeginGetRequestStream(WriteStream, rawRequestData);
     }
     else
     {
         httpRequest.BeginGetResponse(ReadCallback, rawRequestData);
     }
 }
Example #17
0
 /// <summary>Attempts to get data from a web request.</summary>
 /// <param name="request">The HTTP web request.</param>
 /// <param name="method">The OneAll supported HTTP method to use.</param>
 /// <param name="creds">The <see cref="Credential"/> used to authenticate the call, or null for calls not requiring authentication.</param>
 /// <param name="callBack">The call-back to invoke after the request is complete.</param>
 /// <param name="state">The initial state object provided.</param>
 private static void GetAsync(HttpWebRequest request, OneAllMethod method, Credential creds, BinaryReceivedHandler callBack, object state)
 {
     request.SetHTTPMethod(method);
     request.SetBasicAuth(creds);
     request.BeginGetResponse(OnRequestCompleted, new BinaryWebClientState()
     {
         Request = request,
         Callback = callBack,
         State = state
     });
 }
Example #18
0
        public void DownloadDataAsync(HttpWebRequest request, byte[] d,  int millisecondsTimeout,
           RequestCompletedEventHandler completedCallback)
        {
            RequestState state = new RequestState(request, d, millisecondsTimeout, completedCallback, null);

            IAsyncResult result = request.BeginGetResponse(GetResponse, state);

#if !NETFX_CORE
            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
#endif
        }
Example #19
0
        private IAsyncResult BeginGetServerResponse(
            AsyncCallback callback, object state, string method, string command, params string[] parameters)
        {
            Debug.Assert("get".Equals(method, StringComparison.OrdinalIgnoreCase)
                || "set".Equals(method, StringComparison.OrdinalIgnoreCase));

            HttpWebRequest request = HttpWebRequest.CreateHttp(GetUrl(command, parameters));
            this.request = request;
            request.Method = method;
            return request.BeginGetResponse(callback, state);
        }
Example #20
0
        public IAsyncResult BeginGetWeather(string zipCode, AsyncCallback callback, object state)
        {
            _zipCode = zipCode;

            Uri uri = new Uri(String.Format(ServiceUriFormat, zipCode, DateTime.Now.Ticks));

            _request = (HttpWebRequest)HttpWebRequest.Create(uri);
            _request.Method = "GET";

            return _request.BeginGetResponse(callback, state);
        }
Example #21
0
        /// <summary>
        /// Creates the WebRequest object for communicating with the tracker
        /// </summary>
        /// <param name="eventString">Event to report. Can be either "started", "completed", "stopped", or "" (for tracker updates)</param>
        /// <param name="numwant">How many peers to request. Defaults to 50.</param>
        /// <param name="compact">True if we want the tracker to respond in compact form. The tracker ignores this if it does not support it</param>
        /// <returns>WebRequest object</returns>
        private void SendWebRequest(string eventString, int numwant, bool compact,
                                    int bytesUploaded, int bytesDownloaded)
        {
            string newUrl = infofile.AnnounceUrl;

            newUrl += newUrl.IndexOf("?") >= 0 ? "&" : "?";

            newUrl += "info_hash=" + UriEscape(infofile.InfoDigest.Data);
            newUrl += "&peer_id=" + UriEscape(torrent.Session.LocalPeerID.Data);
            newUrl += "&port=" + Config.ActiveConfig.ChosenPort;
            newUrl += "&uploaded=" + bytesUploaded;
            newUrl += "&downloaded=" + bytesDownloaded;
            newUrl += "&left=" + this.file.NumBytesLeft;

            if (Config.ActiveConfig.ServerIP != "")
            {
                newUrl += "&ip=" + Config.ActiveConfig.ServerIP;
            }

            if (numwant > 0)
            {
                newUrl += "&numwant=" + numwant;
            }

            if (compact)
            {
                newUrl += "&compact=1";
                newUrl += "&no_peer_id=1";
            }

//			newUrl += "&key=54644";

            if (eventString != "")
            {
                newUrl += "&event=" + eventString;
            }

            Net.HttpWebRequest request = (Net.HttpWebRequest)Net.WebRequest.Create(newUrl);

            request.KeepAlive = false;
            request.UserAgent = "BitTorrent/3.4.2";
            request.Headers.Add("Cache-Control", "no-cache");
            request.ProtocolVersion = new System.Version(1, 0);

            if (eventString == "stopped" && badTracker)
            {
                return;
            }
            else
            {
                request.BeginGetResponse(new System.AsyncCallback(OnResponse), request);
            }
        }
Example #22
0
        public static void DownloadDataAsync(HttpWebRequest request, int millisecondsTimeout,
            DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
        {
            // Create an object to hold all of the state for this request
            RequestState state = new RequestState(request, null, millisecondsTimeout, null, downloadProgressCallback,
                completedCallback);

            // Start the request for the remote server response
            IAsyncResult result = request.BeginGetResponse(GetResponse, state);
            // Register a timeout for the request
            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
        }
Example #23
0
        internal static void SendRequest(HttpWebRequest requestContainer, Action<string> cb)
        {
            // Note that current design assumes a successfull post will be followed by a getAndRead
            AsyncCallback getAndRead = new AsyncCallback(delegate(IAsyncResult responseResult)
            {
                HttpWebRequest responseContainer = (HttpWebRequest)responseResult.AsyncState;

                try
                {
                    string url = null;
                    HttpWebResponse response = (HttpWebResponse)responseContainer.EndGetResponse(responseResult);

                    Stream s = response.GetResponseStream();

                    XDocument xmlDoc = XDocument.Load(s);

                    // Release the HttpWebResponse
                    response.Close();

                    if (xmlDoc.Element("response") != null)
                    {
                        if (xmlDoc.Element("response").Element("data") != null)
                        {
                            if (xmlDoc.Element("response").Element("data").Element("url") != null)
                            {
                                url = xmlDoc.Element("response").Element("data").Element("url").Value;
                            }
                        }
                    }

                    cb(url);
                }
                catch (WebException we)
                {
                    string error = new StreamReader(we.Response.GetResponseStream()).ReadToEnd();

                    cb(null);
                }
                catch (Exception e)
                {
                    cb(null);
                }
            });

            try
            {
                requestContainer.BeginGetResponse(getAndRead, requestContainer);
            }
            catch (Exception e)
            {
                cb(null);
            }
        }
        void SplashPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.developer.nokia.com/Community/Wiki/Portal:Windows_Phone_UI_Articles"));
                request.BeginGetResponse(new AsyncCallback(ReceiveResponseCallBack), null);
            }
            catch (Exception ex)
            {

            }
        }
Example #25
0
 public void update_url(string url)
 {
     begin_update();
     abort_last_request();
     try
     {//异步读网页
         request = (HttpWebRequest)WebRequest.Create(url);
         request.BeginGetResponse(new AsyncCallback(update_url_part2), null);
     }
     catch (Exception ex) {
         exception_update(ex);
     }
 }
Example #26
0
 void doDownload(string u)
 {
     try
     {
         r = (HttpWebRequest)HttpWebRequest.Create(u);
         r.BeginGetResponse(new AsyncCallback(ResponseReceived), null);
     }
     catch (Exception ex)
     {
         log.Error("Failed in doDownload", ex);
         this.Invoke(new EventHandler(this.Failure));
     }
 }
Example #27
0
        public void GetLatestNews(Action<ObservableCollection<NewsItem>, Exception> callback)
        {
            if (callback !=  null)
            {
                this.Callback = callback;
            }

            Uri rssUri = new Uri("http://feeds.ign.com/ign/games-articles?format=xml", UriKind.Absolute);
            request = (HttpWebRequest)WebRequest.Create(rssUri);

            request = (HttpWebRequest)WebRequest.Create(rssUri);
            request.BeginGetResponse(HandleResponse, null);
        }
        /// <summary>
        /// Handles the button click.
        /// </summary>
        /// <param name="sender">the button</param>
        /// <param name="e">the events args</param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            request = WebRequest.CreateHttp(MainPage.mediaFileLocation);

            // NOTICE
            // Makes this demo code easier but I wouldn't do this on a live phone as it will cause the whole
            // file to download into memory at once.
            //
            // Instead, use the asynchronous methods and read the stream in the backgound and dispatch its
            // data as needed to the ReportGetSampleCompleted call on the UIThread.
            request.AllowReadStreamBuffering = true;
            IAsyncResult result = request.BeginGetResponse(new AsyncCallback(this.RequestCallback), null);
        }
Example #29
0
        public WebRequestResult(HttpWebRequest pRequest, ProxyTranslation pTranslation, AsyncCallback pCallback, HttpContext pContext, object pState)
        {
            context = pContext;
            _request = pRequest;
            _callback = pCallback;
            translation = pTranslation;
            IsCompleted = false;
            AsyncState = pState;

            if (_request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
                _request.BeginGetRequestStream(new AsyncCallback(AsyncReturnStream), this);
            else
                _request.BeginGetResponse(new AsyncCallback(AsyncReturn), this);
        }
Example #30
0
 protected void POST(string URL, string post_message)
 {
     POST_REQUEST = (HttpWebRequest)HttpWebRequest.Create(URL);
     POST_REQUEST.Method = "POST";
     POST_REQUEST.ContentType = "application/x-www-form-urlencoded";
     POST_REQUEST.BeginGetRequestStream(result =>
     {
         Stream post_stream = POST_REQUEST.EndGetRequestStream(result);
         byte[] ba = Encoding.UTF8.GetBytes(post_message);
         post_stream.Write(ba, 0, ba.Length);
         post_stream.Close();
         POST_REQUEST.BeginGetResponse(new AsyncCallback(POST_Method_CallBack),POST_REQUEST);
     }, POST_REQUEST);
 }
Example #31
0
        private void RequestStreamReady(IAsyncResult ar)
        {
            string clientID          = "tungnt92";
            string clientSecret      = "nguyentungvungocthaonguyen";
            String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret));

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)ar.AsyncState;

            byte[]           bytes      = System.Text.Encoding.UTF8.GetBytes(strRequestDetails);
            System.IO.Stream postStream = request.EndGetRequestStream(ar);
            postStream.Write(bytes, 0, bytes.Length);
            postStream.Close();

            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
        }
        public void DownloadFile(Uri source, string target)
        {
            //while (Downloading) { } //NOP - wait for current download to finnish
            string dir = Path.GetDirectoryName(target);
            while (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); }

            Downloading = true;

            _target = target;
            FileNumber++;
            CurrentBytes = 0;

            _request = (HttpWebRequest)HttpWebRequest.Create(source);
            _request.BeginGetResponse(new AsyncCallback(ResponseReceived), Instance);
        }
Example #33
0
 protected void GET(string URL)
 {
     GET_REQUEST = (HttpWebRequest)HttpWebRequest.CreateHttp(URL);
     GET_REQUEST.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1";
     GET_REQUEST.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
     GET_REQUEST.Headers[HttpRequestHeader.AcceptLanguage] = "en-us,en;q=0.5";
     GET_REQUEST.Headers[HttpRequestHeader.Connection] = "keep-alive";
     GET_REQUEST.Headers["Accept-Location"] = "*";
     GET_REQUEST.Headers[HttpRequestHeader.Referer] = "http://www.bing.com/";
     if (this.GetType().ToString() == "Resources.youtube_org")
     {
        GET_REQUEST.Headers[HttpRequestHeader.Host] = "www.youtube-mp3.org";
        GET_REQUEST.Headers[HttpRequestHeader.Referer] = "http://www.youtube-mp3.org/";
     }
     GET_REQUEST.BeginGetResponse(new AsyncCallback(GET_Method_CallBack), GET_REQUEST);
 }
        /// <summary>
        /// Get the response from the call to the given URL as a string.
        /// </summary>
        /// <param name="uri">The URI you're making a GET request to.</param>
        /// <param name="asyncResultHandler">the async callback called when complete.</param>
        /// <param name="state">state to be included in the callback.</param>
        public void GetResponseString(Uri uri, AsyncCallback asyncResultHandler, object state)
        {
            _httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            if (_authenticated)
            {
                _nonceCount++;
                _cnonce = GenerateNewCNonce();

                _httpWebRequest.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(uri);
            }


            _asyncResultHandler = asyncResultHandler;
            _httpWebRequest.BeginGetResponse(RequestCompleted, _httpWebRequest);
        }
Example #35
0
        private void BingRequestStreamReady(IAsyncResult ar)
        {
            // The request stream is ready. Write the request into the POST stream
            string clientID          = "MacTutor";
            string clientSecret      = "8o5famKEXj1/RG0QV92gglvHjQZKHJjsdyw99g5EAIk=";
            String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", WebUtility.UrlEncode(clientID), WebUtility.UrlEncode(clientSecret));

            // note, this isn't a new request -- the original was passed to beginrequeststream, so we're pulling a reference to it back out. It's the same request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)ar.AsyncState;
            // now that we have the working request, write the request details into it
            byte[]           bytes      = System.Text.Encoding.UTF8.GetBytes(strRequestDetails);
            System.IO.Stream postStream = request.EndGetRequestStream(ar);
            postStream.Write(bytes, 0, bytes.Length);
            postStream.Dispose();
            // now that the request is good to go, let's post it to the server
            // and get the response. When done, the async callback will call the
            // GetResponseCallback function
            request.BeginGetResponse(new AsyncCallback(GetBingResponseCallback), request);
        }
Example #36
0
        public static Connection ConnectOverHttpProxy(string remoteHost, int remotePort)
        {
            if (!HttpProxy.Exists)
            {
                throw new InvalidOperationException("Http Proxy has not been set.");
            }

            int availableLocalPort = Server.GetAvailableLocalEndPoint().Port;

            Server fakeProxy = Server.Start(IPAddress.Parse("127.0.0.1"), availableLocalPort);

            Console.WriteLine("\r\nConnectOverHttpProxy: Fake server listening on port {0}", availableLocalPort);

            TunnelWaitHandle taskCompletedEvent = new TunnelWaitHandle();

            fakeProxy.SetObserver(new WebProxyServerObserver(taskCompletedEvent));

            System.Net.HttpWebRequest webRequest = HttpWebRequest.Create("https://" + remoteHost + ":" + remotePort) as HttpWebRequest;
            webRequest.Proxy     = HttpProxy.GenerateLocalProxy(availableLocalPort);
            webRequest.KeepAlive = false;

            webRequest.BeginGetResponse(null, null);

            taskCompletedEvent.WaitOne();

            webRequest.Abort();

            webRequest = null;

            fakeProxy.Stop();

            if (taskCompletedEvent.Result == null)
            {
                throw new System.Exception("Could not connect to remote host");
            }

            Console.WriteLine("nConnectOverHttpProxy: Connected to external net!");

            return(taskCompletedEvent.Result as Connection);
        }
Example #37
0
 /// <summary>
 /// Gets BeginGetResponse implementation of the underlying HttpWebRequest class.
 /// </summary>
 public IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
 {
     return(request.BeginGetResponse(callback, state));
 }