首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过相同的webclient (带cookie)实例发出序列http请求

如何通过相同的webclient (带cookie)实例发出序列http请求
EN

Stack Overflow用户
提问于 2012-11-18 21:58:20
回答 1查看 553关注 0票数 1

请考虑我的情况:

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

我有经验来确认,服务器将写入cookie到客户端,以确保您已登录。但是我们知道,无论是windows phone中的WebClient还是HttpWebRequest类,都只支持异步操作。如果我想实现登录进程,我必须在getVerifyCode()方法的uploadStringCompleted方法中编写代码。我认为这不是最好的做法。例如:

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

代码语言:javascript
复制
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);
    }
}

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

在此之前非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2013-02-23 07:46:59

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

代码语言:javascript
复制
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/主线程的响应。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13440824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档