Getting data back from an HttpWebRequest.BeginGetResponse callback

25,752

Solution 1

You can try the following code,

string url = "http://myserver.com/?page=hello&param2=val2";

    // HTTP web request
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.Method = "POST";
    httpWebRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
    }

    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;

        using (var postStream = webRequest.EndGetRequestStream(asynchronousResult))
        {
           //send yoour data here
        }
        webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
    }

    void GetResponseCallback(IAsyncResult asynchronousResult)
    {

        try
        {
            HttpWebRequest myrequest = (HttpWebRequest)asynchronousResult.AsyncState;
            using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
            {
                System.IO.Stream responseStream = response.GetResponseStream();
                using (var reader = new System.IO.StreamReader(responseStream))
                {
                    data = reader.ReadToEnd();
                }
                responseStream.Close();
            }
        }
        catch (Exception e)
        {
  //Handle Exception
            }
            else
                throw;
        }
    }

Solution 2

 public static string GetPageAsString(Uri address)
    {
        string result = "";

        // Create the web request  
        HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

        // Get response  
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream  

            StreamReader reader = new StreamReader(response.GetResponseStream(), Constants.EncodingType);

            // Read the whole contents and return as a string  
            result = reader.ReadToEnd();
        }

        return result;
    } 
Share:
25,752
Admin
Author by

Admin

Updated on April 03, 2020

Comments

  • Admin
    Admin about 4 years

    I am writing a Windows Phone 8 app that is supposed to send an GET+POST request to a server and parse the answer.

    The code I am using to send the request and to get a response back is the following (it is written in a separate static class):

                    // server to POST to
            string url = "http://myserver.com/?page=hello&param2=val2";
    
            // HTTP web request
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Method = "POST";
    
            // Write the request Asynchronously 
            using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
                                                                     httpWebRequest.EndGetRequestStream, null))
            {
                // Create the post data
                string postData = "pseudo=pseudo&titre=test&texte=\"Contenu du message\"";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    
                // Write the bytes to the stream
                await stream.WriteAsync(byteArray, 0, byteArray.Length);
                stream.Close();
                IAsyncResult ar = httpWebRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), httpWebRequest);
    
            }
    
    
    
        }
    
        private static void GetResponsetStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                //For debug: show results
                System.Diagnostics.Debug.WriteLine(result);
    
    
    
            }
    

    My problem is : I have no idea how to get this answer (the string result) back in my behind-code in my app (or any other method in my app to be honest).

    How could I do that?