reddit的整合Android应用

问题描述:

我要reddit的集成到Android应用程序。我并不需要太多。只有登录后,一个新的链接。
(有点像Facebook上的份额)。

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).

但我挣扎一开始。

任何帮助将b AP preciated。

Any help will b appreciated.

编辑:
以下是我迄今所取得,我得到的modhash和验证码,但是当我试图提交新的链接它给了我这样的:
{JSON:{错误:[[USER_REQUIRED,请登录要做到这一点,空]]}}

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

其中string Cookie则登录检索。当我执行它:

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!

好了,我找到了一个解决方案(也许不是一个完美的人,但它的工作原理)。

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

所以首先下载raw4j reddit的API包装 https://github.com/corydissinger/raw4j

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

在提交一个新的链接应该尽快列入pretty。但如果你将其下载并提交功能将不可pressent(我贴我的变化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:

要RedditApiParameterConstants.java添加这些:

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

和以Reddit.java补充一点:

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;

}

然后就是从该项目建立* .jar文件(如果不包括的话),并把它添加到您的项目。

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.