【问题标题】:How Do You Download a Csv File With Restsharp Without Getting Logged Out?如何在不注销的情况下使用 Restsharp 下载 Csv 文件?
【发布时间】:2018-01-25 15:29:14
【问题描述】:

这是我的代码。 现在,当我运行代码时,从 Console.WriteLine 到终端的输出是正确的,并且是我想要写入 csv 文件的内容。但是,当我检查计算机上的 example.csv 文件时,它只有登录页面的 html,表明我已注销。这里有什么问题?

据我了解,使用 cookiejar 可以让我存储登录信息,即使有额外的请求也应该让我保持登录状态。

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();
        client.Authenticator = new SimpleAuthenticator("username", "xxx", "password", "xxx");
        var request = new RestRequest("/login", Method.POST);


        client.DownloadData(new RestRequest("/file", Method.GET)).SaveAs("example.csv");

        IRestResponse response = client.Execute(request);

        Console.WriteLine(response.Content);
    }

}



class MainClass
{
    public static void Main(string[] args)
    {
        string test = "\r\n";
        ScheduledBilling.report();
        Console.Write(test);

    }
}


}

还有另一个相关的小问题。为什么响应引用原始登录请求时,它会在终端执行并在client.DownloadData中产生新的休息请求?

【问题讨论】:

    标签: c# restsharp


    【解决方案1】:

    您在尝试下载 CSV 之前没有执行登录请求。您的代码应如下所示:

    public static void report()
    {
        //Creates the client
        var client = new RestClient("http://example.com");
        client.CookieContainer = new System.Net.CookieContainer();
        client.Authenticator = new SimpleAuthenticator("username", "xxx", "password", "xxx");
    
        //Creates the request
        var request = new RestRequest("/login", Method.POST);
    
        //Executes the login request
        var response = client.Execute(request);
    
        //This executes a seperate request, hence creating a new requestion
        client.DownloadData(new RestRequest("/file", Method.GET)).SaveAs("example.csv");
    
        Console.WriteLine(response.Content);
    }
    

    【讨论】:

    • 成功了!现在它保存到 csv 文件。很好地解释了,一件事是 writeline 现在生成登录页面的 html 而不是 csv。如果没有分配给第二个请求的变量,我将如何在终端中生成 csv 的内容?
    • @edwrdkm 看看这篇 Stack Overflow 文章stackoverflow.com/questions/29123291/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2023-03-21
    相关资源
    最近更新 更多