如何通过相同的webclient(带cookie)实例生成序列http请求

时间:2012-11-18 13:58:20

标签: c# windows-phone-7 webclient

请考虑我的情况:

我正在开发一个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);
    }
}

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

提前多多感谢。

1 个答案:

答案 0 :(得分: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 /主线程的响应。