请考虑我的情况:
我正在开发一个windows phone 7应用程序,它向我们学校的一个服务器发送HTTP POST请求,以从其中获取一些信息。当你进入网站时,它会显示一个验证码图像,你需要输入你的校号,密码以及验证码才能登录它。然后你就可以访问你想要的任何东西。
我有经验来确认,服务器将写入cookie到客户端,以确保您已登录。但是我们知道,无论是windows phone中的WebClient还是HttpWebRequest类,都只支持异步操作。如果我想实现登录进程,我必须在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);
}
}因此,简而言之,我想知道解决上述问题的最佳实践或设计模式是什么?
在此之前非常感谢。
发布于 2013-02-23 07:46:59
以下是使用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/主线程的响应。
https://stackoverflow.com/questions/13440824
复制相似问题