views:

58

answers:

1

I want to have my c# program automatically post ratings for an episode while logged into my tvdb account. I have done something similar many times using some code i got from http://stackoverflow.com/questions/2798610/login-to-website-and-use-cookie-to-get-source-for-another-page as a guide. Here is my version of it:

    public class WebClientEx : WebClient
    {
        public CookieContainer CookieContainer { get; private set; }

        public WebClientEx()
        {
            CookieContainer = new CookieContainer();
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = CookieContainer;
            }
            return request;
        }
    }


        public static string GetWebDataLoginRequired(string url, string loginUrl, NameValueCollection login_data_values)
    {
        try
        {
            using (var client = new WebClientEx())
            {
                // Authenticate
                client.UploadValues(loginUrl, login_data_values);
                // Download desired page
                return client.DownloadString(url);
            }
        }
        catch
        {
            return null;
        }
    }

    public static readonly NameValueCollection TVDB_LOGIN_DATA = new NameValueCollection
    {
        { "username","username" },
        { "password","password" },
        { "setcookie", "on" }
    };
    public const string TVDB_LOGIN_URL = "http://thetvdb.com/index.php?tab=login&function=Log+In&submit=Log+In";

        string url = String.Format("http://www.thetvdb.com/?function=UserRating&type=episode&itemid={0}&rating={1}&seriesid={2}&seasonid={3}", ep.id, rating, ep.seriesid, ep.seasonid);
        string data = HtmlLib.GetWebDataLoginRequired(url, HtmlLib.TVDB_LOGIN_URL, HtmlLib.TVDB_LOGIN_DATA);

First off, i just want to say that this code works perfectly fine for other websites, by changing the namevaluecollection, however this one is doesnt want to work.

When i do this manually by plugging in the direct result of the string.format into a webbrowser, it works just fine, however with this code it doesnt work. I have tested using packet tracing and fiddler, and i am 100% sure it is logging in correctly, it just loses the login info for the second request.

A: 

The problem is that the original request for the login data was using http://thetvdb.com, whereas the request to rate the episode was using http://www.thetvdb.com (notice the added www.). Spent a few hours debugging this, only to realize it was as simple as http vs http://www.