PuppyKevin
PuppyKevin

Reputation: 3057

Trying to post comments to Reddit with Java

I'm trying to mess around with a program that will log into a reddit account, and post a comment on a thread. So far, here's my login code:

DefaultHttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost("https://ssl.reddit.com/api/login");
    List<NameValuePair> nameValuePairs = new ArrayList<>(4);
    nameValuePairs.add(new BasicNameValuePair("user", "username"));
    nameValuePairs.add(new BasicNameValuePair("passwd", "password"));
    nameValuePairs.add(new BasicNameValuePair("rem", "True"));
    nameValuePairs.add(new BasicNameValuePair("api_type", "json"));

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);

        Header header = response.getFirstHeader("set-cookie");
        String cookie = header.getValue();

        if (cookie.startsWith("reddit_first")) {
            System.out.println("Unable to log in.");
        } else if (cookie.startsWith("reddit_session")) {
            System.out.println("Logged in successfullly.");

            CookieStore cs = new BasicCookieStore();
            System.out.println("Cookie: " + header.getValue());
            BasicClientCookie bcookie = new BasicClientCookie("reddit_session", header.getValue());
            bcookie.setDomain("reddit.com");
            bcookie.setPath("/");
            cs.addCookie(bcookie);
            client.setCookieStore(cs);
            redditCookie = header;
        }

        JSONObject obj = (JSONObject) JSONValue.parse(response.getEntity().getContent());
        JSONObject json = (JSONObject) obj.get("json");
        JSONObject data = (JSONObject) json.get("data");
        modHash = data.get("modhash").toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

And that does work - it reports that it's successfully logged in, and it does store a modhash.

For posting the comment, I have:

post = new HttpPost("https://ssl.reddit.com/api/comment");
post.addHeader(redditCookie);
nameValuePairs = new ArrayList<>(4);
nameValuePairs.add(new BasicNameValuePair("api_type", "json"));
nameValuePairs.add(new BasicNameValuePair("text", imgurLink + "\r\n"));
nameValuePairs.add(new BasicNameValuePair("thing_id", thingId));
nameValuePairs.add(new BasicNameValuePair("uh", modHash));

try {
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    response = client.execute(post);

    obj = (JSONObject) JSONValue.parse(response.getEntity().getContent());
    System.out.println(obj.toJSONString());
} catch (Exception e) {
    e.printStackTrace();
}

Although, when I try sending a comment, it tells me that I need to be logged in to do it. I understand that I have to send the reddit_session cookie to post the comment, but I don't know if I'm doing it correctly.

Upvotes: 2

Views: 1790

Answers (0)

Related Questions