Created
December 19, 2011 10:27
-
-
Save gligoran/1496507 to your computer and use it in GitHub Desktop.
Getting and using reddit_session Cookie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//First login the user and get the reddit_session string | |
public static string GetRedditSessionForUser(string username, string password) | |
{ | |
string json, setCookie; | |
try | |
{ | |
// request & response for login | |
var request = new WebClient(); | |
request.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); | |
string postData = string.Format("user={0}&passwd={1}", username, password); | |
byte[] dataUp = Encoding.ASCII.GetBytes(postData); | |
byte[] dataDown = request.UploadData("http://www.reddit.com/api/login", "POST", dataUp); | |
json = Encoding.ASCII.GetString(dataDown); | |
setCookie = request.ResponseHeaders["Set-Cookie"]; | |
} | |
catch (Exception e) | |
{ | |
// some other error (ie. 502) | |
throw new RedditDownException("Reddit seems to be down, again.", e); | |
} | |
// login successful | |
var redditSession = setCookie.Split(new char[] { ';', ' ', '=' }, StringSplitOptions.RemoveEmptyEntries)[1]; | |
return redditSession; | |
} | |
//Then make the Cookie | |
var cookie = new Cookie("reddit_session", GetRedditSessionForUser(username, password)); | |
cookie.Domain = "reddit.com"; | |
cookie.Path = "/"; | |
//Then you can make requests as a logged-in user | |
CookieWebClient request = new CookieWebClient(); | |
request.CookieContainer.Add(Cookie); | |
var json = request.DownloadString("http://www.reddit.com/user/" + Username + "/about.json"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment