无法使用C#中的httprequest POST登录网站?

时间:2011-12-14 10:06:23

标签: c# httpwebrequest

我正在尝试编写一些代码来登录网站。但它不起作用。请你给我一些建议。这是我的一些代码:

static void Main(string[] args)
    {
        CookieContainer container = new CookieContainer();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://pagehype.com/login.php");
        request.Method = "POST";
        request.Timeout = 10000;
        request.ReadWriteTimeout = 30000;
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) (Prevx 3.0.5)";
        request.CookieContainer = container;

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = "username=user&password=password&processlogin=1&return=";
        byte[] data = encoding.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        Stream newStream = request.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string htmldoc = reader.ReadToEnd();
        response.Close();

        Console.Write(htmldoc);
    }

非常感谢,

2 个答案:

答案 0 :(得分:2)

使用http://www.fiddler2.com/fiddler2/查看您使用浏览器登录时发送的http请求,并确保您在代码中构建的请求是相同的。

答案 1 :(得分:0)

PHP登录使用PHPSESSID cookie。您需要捕获它并将其传递回CookieContainer。这是服务器将您识别为经过身份验证的用户的方式。

cookie在初始响应中的Set-Cookie标头中设置。您需要解析它以在容器中重新创建cookie(不要忘记路径(和域?)

var setCookie = response.GetResponseHeader("Set-Cookie");
response.Close();

container = new CookieContainer();
foreach (var cookie in setCookie.Split(','))
{
    var split = cookie.Split(';');
    string name = split[0].Split('=')[0];
    string value = split[0].Split('=')[1];
    var c = new Cookie(name, value);

    if (cookie.Contains(" Domain="))
        c.Domain = split.Where(x => x.StartsWith(" Domain")).First().Split('=')[1];
    else
    {
        c.Domain = ".pagehype.com";
    }

    if (cookie.Contains(" Path="))
        c.Path = split.Where(x => x.StartsWith(" Path")).First().Split('=')[1];

    container.Add(c);
}

然后将此容器添加到您的请求中。