如何使用Restsharp进行永久身份验证
本文关键字:身份验证 何使用 Restsharp | 更新日期: 2023-09-27 18:04:42
我正在开发一个应用程序,从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
字段,但我必须提出请求,每次我导航到另一个页面,这是不方便的。
我如何永久登录,以便我可以从同一实例发出新的请求?
谢谢!
经过一番研究,我发现答案是饼干。每次发出请求时,响应都有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
来发出进一步的请求,并且我通过它全部登录。
谢谢大家的帮助!