试图用Java发表评论到Reddit

时间:2013-06-27 19:50:13

标签: java api reddit

我正在尝试使用将登录到reddit帐户的程序,并在线程上发表评论。到目前为止,这是我的登录代码:

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();
    }

这确实有用 - 它报告它已成功登录,并且它确实存储了一个modhash。

发布评论时,我有:

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();
}

虽然,当我尝试发送评论时,它告诉我需要登录才能执行此操作。我知道我必须发送reddit_session cookie来发表评论,但我不知道我是否正确地做了。

1 个答案:

答案 0 :(得分:2)

你看过jReddit了吗?它是一个几乎完整的Reddit API Java包装器。