如何使用HttpWebRequest等待web请求完成

本文关键字:请求 web 等待 何使用 HttpWebRequest | 更新日期: 2023-09-27 18:12:10

我正在做一个web请求登录我的web服务,我有一个问题。我需要等到登录完成,然后才结束启动登录的方法,因为我需要返回一个布尔值,表示登录是否正确。在下面的代码中,我在需要等待"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();
}

我读了很多关于这个的书,但是我没有找到解决办法。谢谢大家! !

如何使用HttpWebRequest等待web请求完成

使用异步的新样式:

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

你现在应该不需要调用BeginXXX了——当然微软api已经普遍添加了对基于任务的异步模式的支持。

如果GetResponseAsync不可用,则使用Task.Factory.FromAsync,就像BeginRequestStream一样:

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

注意,因为你正在编写一个async方法,初始的方法调用将会很快完成——但是它将返回一个Task<bool>,只有在异步操作完成时才会完成。因此,您可能也应该在调用代码中等待结果。