-
Notifications
You must be signed in to change notification settings - Fork 127
Quickstart
First and foremost, versions 0.7.0.1 and up only supports OAuth2-based authentication. To get yourself setup with an OAuth2 app, see here.
###Choosing a User-Agent
The first step in using the Reddit API effectively is making sure you're sending a descriptive User-Agent header. This allows Reddit to block buggy versions of your app while not affecting others. An effective User-Agent consists of four parts: The target platform, a unique ID (usually your package), a version, and your Reddit username. Let's say I was creating a script to run on a desktop. My platform would be desktop
, my unique ID (package) would be net.dean.awesomebot
, my version would be 0.1
, and my reddit username would be thatJavaNerd
.
UserAgent myUserAgent = UserAgent.of("desktop", "net.dean.awesomebot", "0.1", "thatJavaNerd");
###Authentication
Now we have the minimum amount of data required to create a RedditClient
, the most significant class in the library.
RedditClient redditClient = new RedditClient(myUserAgent);
Since JRAW works only when using OAuth2, we have to authenticate the RedditClient
, lest it be rendered useless. Fortunately, RedditClient
comes with a helper class: OAuthHelper
. This guide will assume you picked a script app, since those are the easiest to authenticate. If you need to use a web or installed app, see the OAuth2 page.
The first thing we need to do is get our credentials in order. JRAW comes with a Credentials
class to help us organize everything.
Credentials credentials = Credentials.script("<username>", "<password>", "<clientId>", "<clientSecret>");
To use this data, we need to use the RedditClient
's OAuthHelper
. Since the Credentials
we created was for a script, we can make use of OAuthHelper
's easyAuth(Credentials)
method.
OAuthData authData = redditClient.getOAuthHelper().easyAuth(credentials));
Finally, we can notify the RedditClient
that we have been authorized.
redditClient.authenticate(authData);
Now we are fully authorized and are able to make requests to the API successfully! To test it out, try redditClient.me()
.
Note that you will need to renew your access token after one hour. To do this, see the OAuth2 page.