Reddit APIへのリンクを投稿する

Reddit APIへのリンクを投稿する

1. 概要

the seriesのこの2番目の記事では、APIを介してアプリケーションからRedditに投稿するためのいくつかの簡単な機能を構築します。

2. 必要なセキュリティ


Submit a Link to Redditを実行するには、「submit」のscopeを使用してOAuth保護リソースを定義する必要があります。

public OAuth2ProtectedResourceDetails reddit() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setScope(Arrays.asList("identity", "submit"));
    return details;


3. キャプチャは必要ですか?

送信するためにReddithave to fill in a Captchaを初めて使用するユーザー。つまり、Reddit内で特定のカルマしきい値を超える前です。


private String needsCaptcha() {
    String result = redditRestTemplate.getForObject(
      "", String.class);
    return result;

private String getNewCaptcha() {
    HttpHeaders headers = new HttpHeaders();
    HttpEntity req = new HttpEntity(headers);

    Map param = new HashMap();
    param.put("api_type", "json");

    ResponseEntity result = redditRestTemplate.postForEntity(
      "", req, String.class, param);
    String[] split = result.getBody().split(""");
    return split[split.length - 2];

4. The “Submit Post” Form

Next, let’s create the main form for submitting new posts to Reddit. Submitting a Link requires the following details:

  • title – the title of the article

  • url – the URL of the article

  • subreddit – the sub-reddit to submit the link to

So let’s see how we can display this simple submission page:

public String showSubmissionForm(Model model) throws JsonProcessingException, IOException {
    String needsCaptchaResult = needsCaptcha();
    if (needsCaptchaResult.equalsIgnoreCase("true")) {
        String iden = getNewCaptcha();
        model.addAttribute("iden", iden);
    return "submissionForm";

And of course the basic submissionForm.html:


Now – let’s take a look at the final step – submitting the actual link via the Reddit API.

We’ll POST a submit request to Reddit using the parameters from our submissionForm:

@RequestMapping(value = "/api/posts")
public class RedditPostRestController {

    private RedditService service;

    @RequestMapping(method = RequestMethod.POST)
    public List submit(@Valid @RequestBody PostDto postDto) {
        return service.submitPost(postDto);

Here’s the actual method implementation:

public List submitPost(PostDto postDto) {
    MultiValueMap param1 = constructParams(postDto);
    JsonNode node = redditTemplate.submitPost(param1);
    return parseResponse(node);

private MultiValueMap constructParams(PostDto postDto) {
    MultiValueMap param = new LinkedMultiValueMap();
    param.add("title", postDto.getTitle());
    param.add("sr", postDto.getSubreddit());
    param.add("url", postDto.getUrl());
    param.add("iden", postDto.getIden());
    param.add("captcha", postDto.getCaptcha());
    if (postDto.isSendReplies()) {
        param.add("sendReplies", "true");

    param.add("api_type", "json");
    param.add("kind", "link");
    param.add("resubmit", "true");
    param.add("then", "comments");
    return param;

And the simple parsing logic, handling the response from the Reddit API:

private List parseResponse(JsonNode node) {
    String result = "";
    JsonNode errorNode = node.get("json").get("errors").get(0);
    if (errorNode != null) {
        for (JsonNode child : errorNode) {
            result = result + child.toString().replaceAll("\"|null", "") + "
"; } return Arrays.asList(result); } else { if ((node.get("json").get("data") != null) && (node.get("json").get("data").get("url") != null)) { return Arrays.asList("Post submitted successfully", node.get("json").get("data").get("url").asText()); } else { return Arrays.asList("Error Occurred while parsing Response"); } } }

All of this is working with a basic DTO:

public class PostDto {
    private String title;

    private String url;

    private String subreddit;

    private boolean sendReplies;

    private String iden;
    private String captcha;

Finally – the submissionResponse.html:





6. 結論

In this quick tutorial we implemented some basic Submit to Reddit functionality – simplistic but fully functional.

In the next part of this case study, we’ll implement a Schedule Post for Later functionality into our app.

このチュートリアルのfull implementationは、the github projectにあります。これはEclipseベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。