您的位置:首页 > 理论基础 > 计算机网络

[转发]HttpWebRequest模拟登陆,存储Cookie以便登录请求后使用

2016-03-02 15:41 981 查看
转自/article/6222987.html

PostLogin :登录,并保存Cookie

public static string PostLogin(string postData, string requestUrlString, ref CookieContainer cookie)
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
//向服务端请求
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
myRequest.CookieContainer = new CookieContainer();
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
//将请求的结果发送给客户端(界面、应用)
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
cookie.Add(myResponse.Cookies);
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
return reader.ReadToEnd();
}


PostRequest :登录后使用Cookie进行其他操作

public static string PostRequest(string postData, string requestUrlString, CookieContainer cookie)
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
myRequest.CookieContainer = cookie;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
return reader.ReadToEnd();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: