以编程方式登录到站点并将浏览器重定向到已登录状态

时间:2013-04-04 15:17:10

标签: c# httpwebrequest http-post fiddler

我想在点击链接时登录网站,然后使用已登录的会话重定向浏览器。我有一些麻烦,这是我尝试过的:

首先,我从登录站点获取会话cookie:

CookieContainer cookies= new CookieContainer();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://someuri.com");
myHttpWebRequest.CookieContainer = cookies;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();

然后我发布到登录页面进行登录:

HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create("http://signInURL.com");
getRequest.CookieContainer = cookies;
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";

byte[] byteArray = Encoding.ASCII.GetBytes(PostParameterStringWithSignInInfo);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();

HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();

然后我想我需要将cookie设置为客户端:

CookieCollection cooki = getRequest.CookieContainer.GetCookies(new Uri("http://someUri.com"));
for(int i = 0; i < cooki.Count; i++)
{
    Cookie c = cooki[i];
    Response.Cookies.Add(new HttpCookie(c.Name, c.Value));
}

然后重定向到您最终登录的位置:

Response.Redirect("http://URLwhenBeingSignedIn.com");

这不起作用。重定向后我仍然退出。

尝试与Fiddler一起做,并成功登录并重定向:

获取会话cookie:

GET / HTTP/1.1
Content-type: application/x-www-form-urlencoded
Host: someuri.com

发布到登录页面以登录:

POST /signIn HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://someuri.com
Accept-Language: en-GB,en;q=0.7,tr;q=0.3
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Content-Length: 90
DNT: 1
Host: signInURL.com
Pragma: no-cache
Cookie: JSESSIONID=fromBefore; Cookie2=fromBefore

PostParameterStringWithSignInInfo

也许有一种比我现在想象的更简单的方法,你可以看到有效的小提琴请求,如果有的话,我很高兴看到它。

0 个答案:

没有答案