1

请考虑我的情况:

我正在开发一个 windows phone 7 应用程序,它将 HTTP POST 请求发送到我们学校的一台服务器以从中获取一些信息。当您访问该网站时,它会显示一个验证码图像,您需要输入您的学校编号、密码以及验证码才能登录。然后,您可以访问任何您想要的内容。

我有经验证实,服务器会在cookie上写入客户端以确保您已登录。但我们知道Windows手机中的WebClientHttpWebRequest类都只支持异步操作。如果我想实现登录过程,我必须在getVerifyCode() 方法的uploadStringCompleted 方法中编写代码。我认为这不是最佳做法。例如:

(注意:这只是一个例子,不是真正的代码,因为要获取验证码我只需要一个GET方法HTTP请求,我认为它可以很好地说明问题让我感到困惑)

public void getVerifyCode()
{
    webClient.uploadStringCompleted += new uploadStringCompleted(getVerifyCodeCompleted);
    webClient.uploadStringAsync(balabala, balabala, balabala);
}

private void getVerifyCodeCompleted(object sender, uploadStringCompletedArgs e)
{
    if(e.Error == null)
    {
        webClient.uploadStringCompleted -= getVerifyCodeCompleted;

        // start log in 
        // I don't submit a new request inside last request's completed event handler
        // but I can't find a more elegent way to do this.
        webClient.uploadStringCompleted += loginCompleted;
        webClient.uploadStringAsync(balabala, balabala, balabala);
    }
}

所以简而言之,我想知道解决上述问题的最佳实践或设计模式是什么?

提前非常感谢。

4

1 回答 1

0

这是使用 HttpWebRequest.BeginGetRequestStream / EndRequestStream 的代码片段:

HttpWebRequest webRequest = WebRequest.Create(@"https://www.somedomain.com/etc") as HttpWebRequest;
webRequest.ContentType = @"application/x-www-form-urlencoded";
webRequest.Method = "POST";

// Prepare the post data into a byte array
string formValues = string.Format(@"login={0}&password={1}", "someLogin", "somePassword");
byte[] byteArray = Encoding.UTF8.GetBytes(formValues);

// Set the "content-length" header 
webRequest.Headers["Content-Length"] = byteArray.Length.ToString();

// Write POST data
IAsyncResult ar = webRequest.BeginGetRequestStream((ac) => { }, null);
using (Stream requestStream = webRequest.EndGetRequestStream(ar) as Stream)
{
    requestStream.Write(byteArray, 0, byteArray.Length);
    requestStream.Close();
}

// Retrieve the response
string responseContent;    

ar = webRequest.BeginGetResponse((ac) => { }, null);
WebResponse webResponse = webRequest.EndGetResponse(ar) as HttpWebResponse;
try
{
    // do something with the response ...
    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
    {
        responseContent = sr.ReadToEnd();
        sr.Close();
    }
}
finally
{
    webResponse.Close();
}

请注意,您应该使用 ThreadPool.QueueUserWorkItem 执行它,以保持 UI/主线程响应。

于 2013-02-22T23:46:59.420 回答