使用RestSharp下载CSV文件时未保持登录状态的问题及代码疑问
修正后的代码示例
using System; using RestSharp; using RestSharp.Authenticators; using RestSharp.Extensions; namespace Updater { class ScheduledBilling { public static void report() { var client = new RestClient("http://example.com"); client.CookieContainer = new System.Net.CookieContainer(); // 1. 先构造并执行登录请求,获取登录会话cookie var loginRequest = new RestRequest("/login", Method.POST); // SimpleAuthenticator会自动把username和password作为参数添加到请求中 client.Authenticator = new SimpleAuthenticator("username", "xxx", "password", "xxx"); IRestResponse loginResponse = client.Execute(loginRequest); // 可以先检查登录是否成功,比如判断响应状态码或内容 if (!loginResponse.IsSuccessful) { Console.WriteLine("登录失败:" + loginResponse.ErrorMessage); return; } // 2. 登录成功后,再执行下载文件的请求,此时CookieContainer已带上登录会话 client.DownloadData(new RestRequest("/file", Method.GET)).SaveAs("example.csv"); // 输出登录请求的响应(如果没重定向的话是登录结果,重定向的话是跳转后的页面) Console.WriteLine(loginResponse.Content); } } class MainClass { public static void Main(string[] args) { string test = "\r\n"; ScheduledBilling.report(); Console.Write(test); } } }
内容的提问来源于stack exchange,提问作者edwrdkm
相关产品推荐
相关产品推荐

