1

I need to integrate Reddit to android app. I don't need much. Only log in and post a new link. (something like a share on Facebook).

But I am struggling on the very beginning.

Any help will b appreciated.

EDIT: Here is what I made so far, I get the modhash and captcha but when I try to submit new link it gives me this: {"json": {"errors": [["USER_REQUIRED", "please login to do that", null]]}}

 private void getModhash(){
    modhash = dbHandler.getUserModahash();
    if(modhash.equals("")){

        String jsonString = "";
        DefaultHttpClient httpclient = new DefaultHttpClient();

        final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3);
        fields.add(new BasicNameValuePair("user", "my_username"));//will ask for a user to enter the password later
        fields.add(new BasicNameValuePair("passwd", "my_password"));
        fields.add(new BasicNameValuePair("api_type", "json"));

        final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login");

        try {
            request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            jsonString = EntityUtils.toString(entity);

            System.out.println("response from redit = " + jsonString);

            JSONObject jObject = new JSONObject(jsonString);
            modhash = jObject.getJSONObject("json").getJSONObject("data").getString("modhash");
            dbHandler.addRedditModahash(modhash);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

private void getCaptcha(){
    String jsonString = "";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(1);
    fields.add(new BasicNameValuePair("api_type", "json"));

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/new_captcha");

    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        jsonString = EntityUtils.toString(entity);

        System.out.println("CAPTCHA response = " + jsonString);

        JSONObject jObject = new JSONObject(jsonString);
        iden = jObject.getJSONObject("json").getJSONObject("data").getString("iden");
        System.out.println("IDEN = " + iden);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    showCaptcha();
}

private void showCaptcha(){
    // custom dialog
    final Dialog dialog = new Dialog(Share.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    dialog.setContentView(R.layout.dialog_img_edt);
    try {
        URL url = new URL("https://ssl.reddit.com/captcha/" + iden);

        final Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());

        ImageView img = (ImageView) dialog.findViewById(R.id.img_captcha);

        img.setImageBitmap(bmp);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Button btn_dialog_submit = (Button) dialog.findViewById(R.id.btn_captcha);
    final EditText edt_dialog = (EditText) dialog.findViewById(R.id.edt_answer);

    btn_dialog_submit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String answ = edt_dialog.getText().toString();
            if(answ.length() > 0){
                answerToCaptcha = answ;
                postToReddit();
                dialog.dismiss();
            }
            else
                Toast.makeText(getApplicationContext(), "Enter answer to captcha..", Toast.LENGTH_LONG).show();
        }
    });

    dialog.show();
}

private void postToReddit(){
    System.out.println("Captcha iden = " + iden);
    System.out.println("Captcha answer = " + answerToCaptcha);

    String jsonString = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();

    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(14);
    fields.add(new BasicNameValuePair("user", "my_username"));
    fields.add(new BasicNameValuePair("passwd", "my_password"));//just thought that this would solve the problem but it doesn't
    fields.add(new BasicNameValuePair("api_type", "json"));
    fields.add(new BasicNameValuePair("captcha", answerToCaptcha));
    fields.add(new BasicNameValuePair("extension", "json"));
    fields.add(new BasicNameValuePair("iden", "json"));
    fields.add(new BasicNameValuePair("kind", iden));
    fields.add(new BasicNameValuePair("resubmit", "true"));
    fields.add(new BasicNameValuePair("save", "true"));
    fields.add(new BasicNameValuePair("sendreplies", "true"));
    fields.add(new BasicNameValuePair("sr", "Money"));
    fields.add(new BasicNameValuePair("text", "We will beat ANY qoute from ANY Bank! We will transfer your money FEE FREE!"));
    fields.add(new BasicNameValuePair("then", "comments"));
    fields.add(new BasicNameValuePair("title", "Check this cool app"));
    fields.add(new BasicNameValuePair("url", "http://www.the_link_to_app.com/"));

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/submit");

    request.addHeader("X-Modhash", modhash);
    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        jsonString = EntityUtils.toString(entity);

        System.out.println("response from redit = " + jsonString);

        JSONObject jObject = new JSONObject(jsonString);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

I also tried to add Cookie, but that didn't helped:

    CookieStore cookieStore = new BasicCookieStore();
    Cookie cookiee = new BasicClientCookie("Cookie", cookie);
    cookieStore.addCookie(cookiee);

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

Where string cookie is retrieved from login. and when I execute the it:

    HttpResponse response = httpclient.execute(request, localContext);

But that didn't helped.. same error message.

Any ideas where is the mistake? Or I try to do that in a wrong way? Any help please!

4
  • What have you tried? Have you read the Reddit Developer Api ? reddit.com/dev/api
    – Tyler
    Nov 18, 2013 at 16:22
  • What are you struggling with? You need to ask more specific questions Nov 18, 2013 at 17:06
  • Well right now I managed to get the modhash for the user and get the captcha which is neccessary to posting new comments/links. But when I try to make a new link I get the response: {"json": {"errors": [["USER_REQUIRED", "please login to do that", null]]}} I will eddit my question with the code so far
    – Mantas
    Nov 20, 2013 at 23:41
  • TylerAndFriends - yes I have, but all they said there is that you need mdhash to compose new comment/link.: "The preferred way to send a modhash is to include an X-Modhash custom HTTP header with your requests." and thats what I am doing.. I think..
    – Mantas
    Nov 21, 2013 at 1:24

1 Answer 1

0

Ok, so I found a solution for this (maybe not a perfect one but it works).

So first of all download the raw4j reddit api wrapper https://github.com/corydissinger/raw4j

The submit a new link should be included pretty soon. But if you will download it and the submit function will not be pressent (I posted my changes to the developer of raw4j but don't know when he will update it) add these:

To "RedditApiParameterConstants.java" add these:

public static final String CAPTCHA_ANSWER       = "captcha";
public static final String EXTENSION            = "extension";
public static final String IDEN                 = "iden";
public static final String KIND                 = "kind";
public static final String RESUBMIT             = "resubmit";
public static final String SAVE                 = "save";
public static final String SEND_REPLIES         = "sendreplies";
public static final String SUB_REDDIT           = "sr";
public static final String THEN                 = "then";
public static final String TITLE                = "title";
public static final String URL                  = "url";

And to the "Reddit.java" add this:

 public RedditJsonMessage newSubmitt(String captchaResponse, String extension, String iden, String kind,
    boolean resubmit, boolean save, boolean sendreplies, String sub_reddit, String text, String then, String title, String url_to_post) throws RedditException {
final List<String> path = new ArrayList<String>(2);
final Map<String, String> form = new HashMap<String, String>(13);

path.add(RedditApiResourceConstants.API);
path.add(RedditApiResourceConstants.SUBMIT);

form.put(RedditApiParameterConstants.API_TYPE, RedditApiParameterConstants.JSON);
form.put(RedditApiParameterConstants.CAPTCHA_ANSWER, captchaResponse);
form.put(RedditApiParameterConstants.EXTENSION, extension);
form.put(RedditApiParameterConstants.IDEN, iden);
form.put(RedditApiParameterConstants.KIND, kind);
form.put(RedditApiParameterConstants.RESUBMIT, String.valueOf(resubmit));
form.put(RedditApiParameterConstants.SAVE, String.valueOf(save));
form.put(RedditApiParameterConstants.SEND_REPLIES, String.valueOf(sendreplies));
form.put(RedditApiParameterConstants.SUB_REDDIT, sub_reddit);
form.put(RedditApiParameterConstants.TEXT, text);
form.put(RedditApiParameterConstants.THEN, then);
form.put(RedditApiParameterConstants.TITLE, title);
form.put(RedditApiParameterConstants.URL, url_to_post);

final RedditRequestInput requestInput = new RedditRequestInput(path, null, form);
final RedditRequestResponse response = requestor.executePost(requestInput);
//System.out.println("Response From Reddit = " + response.toString());
final RedditJsonParser parser = new RedditJsonParser(response.getBody());
final RedditJsonMessage message = parser.parseJsonMessage();

if (!message.getErrors().isEmpty()){
    throw new RedditException("Got errors while submiting the link: " + message.toString());
}

return message;

}

And then just build the *.jar file (if it was not included) from that project and add it to your project.

Hope this will save some time for other developers.

8
  • you didnt pass username and password? Feb 10, 2015 at 6:07
  • username and password is passed on authorization. This is only the method which I added to the github.com/corydissinger/raw4j library. I am not sure how it was changed as the last time I checked that library was like one and a half year ago... Try to include raw4j in your java code and look at github.com/corydissinger/raw4j/blob/master/IMPLEMENTED_CALLS.md for usage instructions.
    – Mantas
    Feb 11, 2015 at 11:31
  • i already seen this library but there are missing files i think. in that library, there is no file name like "RedditJsonMessage".. Feb 11, 2015 at 11:36
  • Its in raw4j/src/main/java/com/cd/reddit/json/mapping/RedditJsonMessage.java Have you tried adding public RedditJsonMessage newSubmitt(..) method from my answer to the Reddit.java?
    – Mantas
    Feb 11, 2015 at 15:20
  • yeah but as per this link, reddit.com/r/redditdev/comments/2ujhkr/… .it will deprecate. so this is not right solution i think. right? Feb 12, 2015 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.