1

谁能告诉我如何在 Twitter 中使用仅限应用程序的 oauth?我必须在我的应用程序中实现它,但我在网上找不到任何新 api 1.1 的教程。举个例子会好很多……

4

1 回答 1

1

您好,以下代码包括如何使用仅限应用程序的 OAuth 和获取 user_timeline。

  1. 下载这个库http://loopj.com/android-async-http/
  2. 使用此代码

    /*
     * -url user_timeline 
     * -client and asyncHttpResponseHandler is used to get timeline
     */
    String url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=<NAME>";
    AsyncHttpClient client = new AsyncHttpClient();
    AsyncHttpResponseHandler asyncHttpResponseHandler = new AsyncHttpResponseHandler() {
    
      public void onSuccess(String response) {
         /*--------- DidReceiveData ---------*/
         Log.e("", "JSON FILE "+" response " + response);
      };
    };
    
    /*
     * OAuth Starts Here
     */
    RequestParams requestParams = new RequestParams();
    requestParams.put("grant_type", "client_credentials");
    AsyncHttpClient httpClient = new AsyncHttpClient();
    httpClient.addHeader("Authorization", "Basic " + Base64.encodeToString((CONSUMER_KEY + ":" + CONSUMER_SECRET).getBytes(), Base64.NO_WRAP));
    httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    httpClient.post("https://api.twitter.com/oauth2/token", requestParams, new AsyncHttpResponseHandler() {
    
            public void onSuccess(String responce) {
    
                try {
                    JSONObject jsonObject = new JSONObject(
                            responce);
                    Log.e("", "token_type " + jsonObject.getString("token_type") + " access_token " + jsonObject.getString("access_token"));
                    client.addHeader("Authorization", jsonObject.getString("token_type") + " " + jsonObject.getString("access_token"));
                    client.get(url, asyncHttpResponseHandler);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            };
    
            public void onFailure(Throwable error, String response) {
                Log.e("", "error " + error.toString() + " response " + response);
    
            };
    
        });
    
于 2013-06-30T09:36:47.237 回答