Reddit集成到Android应用程序

时间:2013-11-18 15:58:48

标签: android api integration reddit

我需要将Reddit集成到Android应用程序中。我不需要太多。仅登录并发布新链接。 (像Facebook上的分享)。

但我一开始就在苦苦挣扎。

任何帮助都会受到赞赏。

编辑: 这是我到目前为止所做的,我得到modhash和验证码但是当我尝试提交新链接时它给了我这个: {“json”:{“errors”:[[“USER_REQUIRED”,“请登录以执行此操作”,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();
    }

}

我也尝试添加Cookie,但这没有帮助:

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

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

从登录中检索字符串cookie。当我执行它时:

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

但这没有帮助..同样的错误信息。

任何想法都是错误的?或者我试图以错误的方式做到这一点? 请帮忙!

1 个答案:

答案 0 :(得分:0)

好的,所以我找到了一个解决方案(也许不是一个完美的解决方案,但它有效)。

首先下载raw4j reddit api包装器https://github.com/corydissinger/raw4j

很快就会提交一个新链接。但是如果你下载它并且提交函数不会被提交(我将我的更改发布到raw4j的开发者但不知道他什么时候会更新它)添加这些:

要“RedditApiParameterConstants.java”添加以下内容:

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";

并向“Reddit.java”添加:

 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;

}

然后只需从该项目构建* .jar文件(如果未包含)并将其添加到项目中。

希望这会为其他开发者节省一些时间。