-
Notifications
You must be signed in to change notification settings - Fork 127
Quickstart
###Adding the Dependency
JRAW is hosted on Bintray's jCenter.
Gradle:
repositories {
jcenter()
}
dependencies {
compile "net.dean.jraw:JRAW:$jrawVersion"
}
Maven:
Add jCenter (https://jcenter.bintray.com
) to your repositories and then add the dependency:
<dependency>
<groupId>net.dean.jraw</groupId>
<artifactId>JRAW</artifactId>
<version>${jraw.version}</version>
</dependency>
###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 a Reddit username. Say, for example, someone was creating an app called "Awesome App." Their platform would be android
, their unique ID (package) could be com.example.awesomeapp
, and their version could be something like 0.1
. For the sake of example, let's say their username is 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
:
RedditClient redditClient = new RedditClient(myUserAgent);
Since JRAW only supports OAuth2, we have to authenticate the RedditClient
before we can get any useful responses from the API. 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.