简体   繁体   中英

How Do You Download a Csv File With Restsharp Without Getting Logged Out?

Here is my code. Now When I run the code, the output to my terminal from Console.WriteLine is correct and is what I want written in my csv file. However, when I check the example.csv file on my computer, it just has the html of the sign in page indicating that I was logged out. What is the problem here?

From my understanding using cookiejar allows me to store logins and should keep me logged in even with extra requests.

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);

    }
}


}

Also another small related question. Why does it execute and produce in the terminal the new rest request in client.DownloadData when response refers to the original log-in request?

You didn't execute the login request before trying to download the CSV. Your code should look something like this:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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