无法在c#中使用httprequest POST登录网站

本文关键字:httprequest POST 登录 网站 | 更新日期: 2023-09-27 18:18:01

我想写一点代码登录到一个网站。但这行不通。你能给我一些建议吗?这是我的一小段代码:

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);
    }
许多谢谢,

无法在c#中使用httprequest POST登录网站

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

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

在初始响应的set - cookie头中设置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);
}