how to wait until a web request with HttpWebRequest is finished?

Luis López

I am doing a web request to login in a my web services and I have a problem. I need to wait until the login is finished before end the method that launchs the login because I need to return a boolean value that represents if the login was correct or not. In the following code I put a comment where I need wait for the result of "httpWebRequest.BeginGetResponse(...)"

public async Task<bool> login(string user, string passwrd)
{
    mLoginData.setUserName(user);
    mLoginData.setPasswd(passwrd);

    string serviceURL = mBaseURL + "/pwpcloud/service/user/login";

    //build the REST request
    // HTTP web request
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceURL);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";

    // Write the request Asynchronously 
    using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null))
    {

        string parameters = "{\"username\":\"" + user + "\",\"password\":\"" + passwrd + "\"}";
        byte[] byteArray = Encoding.UTF8.GetBytes(parameters);

        // Write the bytes to the stream
        await stream.WriteAsync(byteArray, 0, byteArray.Length);
    }
    //httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingLoginResponse), httpWebRequest);
    httpWebRequest.BeginGetResponse(r =>
       {
           using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.EndGetResponse(r))
           {
               string data;

               // Read the response into a Stream object. 
               Stream responseStream = response.GetResponseStream();
               using (var reader = new StreamReader(responseStream))
               {
                   data = reader.ReadToEnd();
               }
               responseStream.Close();
               if (response.StatusCode == HttpStatusCode.OK)
               {
                   dynamic jsonData = JObject.Parse(data);
                   string token = jsonData.token;
                   mLoginData.setToken(token);
                   string userId = jsonData.userId;
                   mLoginData.setUserID(userId);
                   mLoginData.setLogged(true);
                   //guardamos los valores en el isolatedStorageSettings para que persistan. 
                   App.settings.Clear();
                   App.settings.Add("userId", mLoginData.getUserID());
                   App.settings.Add("token", mLoginData.getToken());
                   App.settings.Add("userName", mLoginData.getUserName());
                   App.settings.Add("passwd", mLoginData.getPasswd());
                   App.settings.Add("logged", mLoginData.isLogged());
                   App.settings.Save();
               }
               else
               {
                   if (CultureInfo.CurrentUICulture.Name.ToString().Contains("ES"))
                   {
                       if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.BadRequest)
                       {
                           MessageBox.Show("Usuario o contraseña incorrectos");
                       }
                       else
                       {
                           MessageBox.Show("Error de conexión.");
                       }
                   }
                   else
                   {
                       if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.BadRequest)
                       {
                           MessageBox.Show("User or password were incorrect");
                       }
                       else
                       {
                           MessageBox.Show("NNetwork connection error");
                       }
                   }
               }
           }
       }, null);
    //here i need wait for the result of the webrequest to return true if the login was successfull.
    return mLoginData.isLogged();
}

I read a lot about this buf I didn't find the solution. Thanks everyone!!!

Jon Skeet

Just use the newer style of asynchrony:

using (var response = (HttpWebResponse) await request.GetResponseAsync())
{
    ...
}

You shouldn't need to call BeginXXX much now - certainly the Microsoft APIs have pretty universally added support for the Task-based Asynchronous Pattern.

If GetResponseAsync isn't available, use Task.Factory.FromAsync just as you have for BeginRequestStream:

var responseTask = Task.Factory.FromAsync<WebResponse>
                                      (httpWebRequest.BeginGetResponse,
                                       httpWebRequest.EndGetResponse,
                                       null);
using (var response = (HttpWebResponse) await responseTask)
{
}

Note that because you're writing an async method, the initial method call will still finish quickly - but it will return a Task<bool> which will only complete when the async operation has completed. So you should probably be awaiting the result in the calling code, too.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to wait until an http request is finished before moving on?

From Dev

wait until completion block not finished in AFJSONRPCClient request

From Dev

wait until completion block not finished in AFJSONRPCClient request

From Java

How to wait until all async calls are finished

From Dev

How to wait until an animation is finished in Swift?

From Dev

How to wait until all NSOperations is finished?

From Dev

How to wait until some jQuery methods are finished?

From Dev

How to wait until networking by Alamofire has finished?

From Dev

How to wait until my batch file is finished

From Dev

How to get jQuery to wait until an animation is finished?

From Dev

Android - How to wait until a SnapshotListener has finished?

From Dev

Wait until function is finished

From Dev

Selenium wait.until to check ajax request finished is throw error

From Dev

How to wait until all tasks are finished before running code

From Dev

How to wait until all tasks finished without blocking UI thread?

From Dev

How to make python wait until the previous task is finished?

From Dev

In NodeJs how can I wait until my http get is finished?

From Dev

How to make Gulp wait until dest file is finished?

From Dev

How do I make an Excel RefreshAll wait to close until finished?

From Dev

How to make python wait until the previous task is finished?

From Dev

How can I wait until NSXMLParserDelegate methods finished?

From Dev

How to make JS wait until protocol execution finished

From Dev

How to make a python Script wait until download has finished

From Dev

How to wait until canvas has finished re-rendering?

From Dev

Wait until forEach loop is finished?

From Dev

Wait until gobalEval has finished

From Dev

On click myFunction and wait until it is finished

From Dev

Wait until NSURLConnection sendAsynchronousRequest is finished

From Dev

Android AsyncTask wait until finished

Related Related

  1. 1

    How to wait until an http request is finished before moving on?

  2. 2

    wait until completion block not finished in AFJSONRPCClient request

  3. 3

    wait until completion block not finished in AFJSONRPCClient request

  4. 4

    How to wait until all async calls are finished

  5. 5

    How to wait until an animation is finished in Swift?

  6. 6

    How to wait until all NSOperations is finished?

  7. 7

    How to wait until some jQuery methods are finished?

  8. 8

    How to wait until networking by Alamofire has finished?

  9. 9

    How to wait until my batch file is finished

  10. 10

    How to get jQuery to wait until an animation is finished?

  11. 11

    Android - How to wait until a SnapshotListener has finished?

  12. 12

    Wait until function is finished

  13. 13

    Selenium wait.until to check ajax request finished is throw error

  14. 14

    How to wait until all tasks are finished before running code

  15. 15

    How to wait until all tasks finished without blocking UI thread?

  16. 16

    How to make python wait until the previous task is finished?

  17. 17

    In NodeJs how can I wait until my http get is finished?

  18. 18

    How to make Gulp wait until dest file is finished?

  19. 19

    How do I make an Excel RefreshAll wait to close until finished?

  20. 20

    How to make python wait until the previous task is finished?

  21. 21

    How can I wait until NSXMLParserDelegate methods finished?

  22. 22

    How to make JS wait until protocol execution finished

  23. 23

    How to make a python Script wait until download has finished

  24. 24

    How to wait until canvas has finished re-rendering?

  25. 25

    Wait until forEach loop is finished?

  26. 26

    Wait until gobalEval has finished

  27. 27

    On click myFunction and wait until it is finished

  28. 28

    Wait until NSURLConnection sendAsynchronousRequest is finished

  29. 29

    Android AsyncTask wait until finished

HotTag

Archive