我正在尝试以编程方式浏览网站,但是,在我最初成功登录后,之后的任何后续请求似乎都会将我退出,即使我将从上一个响应中检索到的cookie传递给下一个请求。
void Main()
{
var response = GetResponse(
@"https://www.somewebsite.co.uk/account/signin",
RequestMethod.Post,
string.Format("Credentials.Email={0}&Credentials.Password={1}", "test@test.co.uk", "password")
);
var cookiesToPersist = response.Cookies;
var nextResponse = GetResponse(
@"http://www.somewebsite.co.uk/news",
RequestMethod.Post,
string.Empty,
cookiesToPersist
);
}
public HttpWebResponse GetResponse(string url, RequestMethod method, string postData, CookieCollection cookies = null)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
if(cookies == null)
request.CookieContainer.Add(new CookieCollection());
else
request.CookieContainer.Add(cookies);
request.Dump();
request.Method = (method == RequestMethod.Post) ? WebRequestMethods.Http.Post : WebRequestMethods.Http.Get;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
request.AllowWriteStreamBuffering = true;
request.ProtocolVersion = HttpVersion.Version11;
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
var byteArray = Encoding.ASCII.GetBytes(postData);
request.ContentLength = byteArray.Length;
var stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
return (HttpWebResponse)request.GetResponse();
}
public enum RequestMethod
{
Post,
Get
}
仍然关注http请求/回复,所以如果这是一个荒谬的简单问题,我道歉。任何帮助将不胜感激。