C#使用HttpWebRequest Post方法不起作用

时间:2013-10-06 19:13:30

标签: c# httpwebrequest

嘿,我正在试图找出使用HttpWebRequest对登录页面做一个Post请求,比如yahoo mail,并检查返回的页面源。

但是使用我的Post方法我仍然有登录页面。

这是我的方法:

public static string GetResponse(string sURL, ref CookieContainer cookies, string sParameters)
    {
        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(sURL);
        httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
        httpRequest.CookieContainer = cookies;
        httpRequest.Method = "Post";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        httpRequest.ContentLength = sParameters.Length;
        httpRequest.AllowAutoRedirect = true;            

        using (Stream stream = httpRequest.GetRequestStream())
        {
            stream.Write(Encoding.UTF8.GetBytes(sParameters), 0, sParameters.Length);
        }

        HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();

        string sResponse;
        using (Stream stream = httpWebResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(936));
            sResponse = reader.ReadToEnd();
        }

        return sResponse;
    }

调用该方法的代码是:

        string sParameter = ".tries=1&.src=ym&.md5=&.hash=&.js=&.last=&promo=&.intl=us&.lang=en-US&.bypass=&.partner=&.u=eip09319532h1&.v=0&.challenge=3QjvX9eEFtJRrABhZp9kgS9IT.VO&.yplus=&.emailCode=&pkg=&stepid=&.ev=&hasMsgr=0&.chkP=Y&.done=http%3A%2F%2Fmail.yahoo.com&.pd=ym_ver%3D0%26c%3D%26ivt%3D%26sg%3D&.ws=1&.cp=0&nr=0&pad=3&aad=3&login=username%40yahoo.com&passwd=xxxxx&.persistent=&.save=&passwd_raw=";
        System.Net.CookieContainer coookies = null ;
        string sResponse;

        sResponse = GetResponse(sUrl, ref coookies, sParameter);

字符串sParameter是通过检查在Firefox的Firebug插件中发布到服务器的数据获得的。但是在我上面发布的参数中,我屏蔽了我的用户ID和密码。

我想重新使用会话,所以我传递了一个CookieContainer对象作为该方法的参考。

它编译并运行,但返回给我的页面未登录状态。

我已经在stackoverflow上阅读了几个类似的问题,但仍然无法使我的方法工作。感谢您的帮助。

0 个答案:

没有答案