如何使用Restsharp永久进行身份验证

时间:2015-07-27 02:37:58

标签: c# rest authentication html-agility-pack restsharp

我正在开发一个从Web提取数据并使用HtmlAgilityPack解析它的应用程序。但是,不是那么直接,登录需要访问数据。

我正在使用Restsharp进行身份验证:

        //class definitions 
        request = new RestRequest("http://allpoetry.com/login", Method.POST);
        request.AddParameter("utf8", "%E2%9C%93");
        request.AddParameter("authenticity_token", "Lr+JtLv7TkZrS73u5scRPbWhuUYDaVF7vd6lkKFF3FKYqNKHircT9v5WCT9EkneTJRsKXaA6nf6fiWopDB0INw==");
        request.AddParameter("referer", url);  // url to the page I want to go
        request.AddParameter("user[name]", "username");
        request.AddParameter("user[password]", "password");
        request.AddParameter("commit", "Log in");
        request.AddHeader("content-type", "application/x-www-form-urlencoded");
        response = client.Execute(request);

这很好用,但问题是我无法永久登录,我无法使用这个RestRequest类实例发出另一个请求,它给出了我没有登录的错误。我找到了解决办法但它不适用于某些页面,基本上我将url放入referer字段,但每次导航到另一页时我都要提出请求,这很不方便。

如何永久登录,以便我可以从同一个实例发出新请求?

谢谢!

1 个答案:

答案 0 :(得分:2)

经过一番研究,我发现答案是饼干。每次发出请求时,响应都有cookie。 我用过像这样的饼干。

response = client.Execute(request)后我添加了这个:

        request.Resource = url;
        request.Method = Method.GET;
        foreach (var cookie in response.Cookies)
        {
            request.AddCookie(cookie.Name , cookie.Value);  //this adds every cookie in the previous response.
        }
        response = client.Execute(request);
       //use the response as required

这不创建新实例,但使用相同的request进行进一步的请求,我通过它登录。

谢谢大家的帮助!

相关问题