grumlu
grumlu

Reputation: 25

Getting data back from an HttpWebRequest.BeginGetResponse callback

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?

Upvotes: 2

Views: 26281

Answers (4)

Elif&#214;lmez
Elif&#214;lmez

Reputation: 49

 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;
    } 

Upvotes: 4

Developer
Developer

Reputation: 4321

You can: make a global variable in App.xaml.cs: public string result;

In code use it as

(App.Current as App).result = httpWebStreamReader.ReadToEnd();

If you will need to get notified in your current active page when the result is updated - use delegates after you get the response which will signal to your page.

Upvotes: -1

Aju
Aju

Reputation: 806

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;
        }
    }

Upvotes: 5

David d C e Freitas
David d C e Freitas

Reputation: 7511

Does it have to be a static class? Because if you have a new webrequest object for each request, then each response will come back into it's own object.v

You need to put the result somewhere that you can access it from the place you want to use it. e.g. if you put it into another public static variable member then you can read it off where you need to. But you probably need to signal the UI to action it, or bind it to the UI. If you use a static place to store it, then you will only have one active at a time. Unless you add it to a static list of items or results that you are working with

See also: http://blogs.msdn.com/b/devfish/archive/2011/04/07/httpwebrequest-fundamentals-windows-phone-services-consumption-part-2.aspx

Upvotes: 0

Related Questions