简体   繁体   English

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

[英]How to authenticate permanently using Restsharp

I am developing an application that pulls data from web and parses it using HtmlAgilityPack. 我正在开发一个从Web提取数据并使用HtmlAgilityPack对其进行解析的应用程序。 However, its not that straight-forward, login is required to access the data. 但是,访问数据并非必须如此简单。

I am using Restsharp to authenticate like this: 我正在使用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);

This works perfectly but the problem is that I can't Login permanently, i can't make another request using this instance of RestRequest class, it gives the error that I am not logged in. I have found a work-around but it doesn't work with some pages, basically I put the url into the referer field but I have to make request every time I navigate to another page and this is inconvenient. 这可以正常工作,但问题是我无法永久登录,我无法使用RestRequest类的该实例发出另一个请求,它给出了我未登录的错误。我找到了一种解决方法,但它没有某些页面无法使用,基本上我将url放入了referer字段,但是每次我导航到另一个页面时都必须发出请求,这很不方便。

How do I login permanently, so I can make new request from the same instance? 如何永久登录,以便可以从同一实例发出新请求?

Thank you! 谢谢!

After some research, I found that the answer is cookies. 经过研究,我发现答案是饼干。 Each time a request is made, the response has cookies. 每次发出请求时,响应中都有cookie。 I used the cookies like this. 我用这样的饼干。

After response = client.Execute(request) I added this: 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

This doesn't create a new instance but uses the same request to make further requests and I am logged in through it all. 这不会创建新实例,但会使用相同的request进行其他请求,因此我已全部登录。

Thank you everyone for your help! 谢谢你们每一个人的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM