2

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?

edwrdkm
  • 87
  • 3
  • 8

1 Answers1

3

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);
}
tj-cappelletti
  • 1,774
  • 12
  • 19
  • It worked! Now it saves to the csv file. Beautifully explained, one thing is that the writeline now produces the html of the signin page and not the csv. How would I produce the content of the csv in terminal if there is no variable assigned to the second request? – edwrdkm Jan 25 '18 at 20:05
  • @edwrdkm Take a look at this Stack Overflow article https://stackoverflow.com/questions/29123291/how-to-use-restsharp-to-download-file – tj-cappelletti Jan 26 '18 at 01:39