Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Oauth to call yahoo api in android

I want to use the Yahoo API to get login user's email in Android. I already have got access token and user GUID, but the next step to get user email is not working.

I got the following response message:

{oauth=WWW-Authenticate: OAuth oauth_problem="OST_OAUTH_SIGNATURE_INVALID_ERROR", realm="yahooapis.com"}

My code can be found here and the problem is documented here at line 179.

Please help me to resolve this issue.

like image 773
Wendell Avatar asked Feb 12 '23 17:02

Wendell


1 Answers

I got an answer

Full Code :

public class YahooScreen extends Activity {
    private static final String REQUEST_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_request_token";
    private static final String AUTHORIZE_WEBSITE_URL   ="https://api.login.yahoo.com/oauth/v2/request_auth";
    private static final String ACCESS_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_token";

    static final String YAHOO_CALLBACK_URL = "YOUR_YAHOO_CALLBACK_URL";
    static final String YAHOO_CONSUMER_KEY = "YOUR_YAHOO_CONSUMER_KEY";
    static final String YAHOO_CONSUMER_SECRET = "YOUR_YAHOO_CONSUMER_SECRET";

    private String oAuthVerifier;

    CommonsHttpOAuthConsumer mainConsumer;
    CommonsHttpOAuthProvider mainProvider;

    private Button button1;
    private OnClickListener button1_onclick = new OnClickListener()
    {
         public void onClick(View v)
         {
             new OAuthRequestTokenTask(v.getContext(),mainConsumer,mainProvider).execute();
         }
    };

    private Button button2;
    private OnClickListener button2_onclick = new OnClickListener()
    {
         public void onClick(View v)
         {
             new OAuthGetAccessTokenTask().execute();
         }
    };

    private Button button3;
    private OnClickListener button3_onclick = new OnClickListener()
    {
         public void onClick(View v)
         {
             getGUID();
         }
    };

    private Button button4;
    private OnClickListener button4_onclick = new OnClickListener()
    {
         public void onClick(View v)
         {
             showToken();
         }
    };

    private Button button5;
    private OnClickListener button5_onclick = new OnClickListener()
    {
         public void onClick(View v)
         {
             getProfile();
         }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.mainConsumer = new CommonsHttpOAuthConsumer(YAHOO_CONSUMER_KEY, YAHOO_CONSUMER_SECRET);
        this.mainProvider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL, AUTHORIZE_WEBSITE_URL);
        //this.mainConsumer.setSigningStrategy(new YahooAuthorizationHeaderSigningStrategy());

        // It turns out this was the missing thing to making standard Activity launch mode work
        //this.mainProvider.setOAuth10a(true);

        // get request
        button1 = (Button) this.findViewById(R.id.button1);
        button1.setOnClickListener(button1_onclick);

        // access token
        button2 = (Button) this.findViewById(R.id.button2);
        button2.setOnClickListener(button2_onclick);

        // guid
        button3 = (Button) this.findViewById(R.id.button3);
        button3.setOnClickListener(button3_onclick);

        // show token
        button4 = (Button) this.findViewById(R.id.button4);
        button4.setOnClickListener(button4_onclick);

        // Profile
        button5 = (Button) this.findViewById(R.id.button5);
        button5.setOnClickListener(button5_onclick);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Toast.makeText(getApplicationContext(), "OnNewIntent - It works!",
                Toast.LENGTH_LONG).show();
        Uri uriData = intent.getData();
        if (uriData != null && uriData.toString().startsWith(YAHOO_CALLBACK_URL)) {
            setVerifier(uriData.getQueryParameter("oauth_verifier"));
        }
        super.onNewIntent(intent);
    }

    class OAuthRequestTokenTask extends AsyncTask<Void, Void, String> {

        final String TAG = getClass().getName();
        private Context context;
        private OAuthProvider provider;
        private OAuthConsumer consumer;

        public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
            this.context = context;
            this.consumer = consumer;
            this.provider = provider;
        }

        @Override
        protected String doInBackground(Void... params) {

            try {
                Log.i(TAG, "Retrieving request token from Google servers");
                final String url = provider.retrieveRequestToken(consumer, YAHOO_CALLBACK_URL);
                Log.i(TAG, "Popping a browser with the authorize URL : " + url);
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                context.startActivity(intent);

                return url;
            } catch (Exception e) {
                Log.e(TAG, "Error during OAUth retrieve request token", e);
            }

            return null;
        }

        /* (non-Javadoc)
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(String result) {
            Log.i(TAG, "onPostExecute result : " + result);
            super.onPostExecute(result);

        } 
    }

    public class OAuthGetAccessTokenTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                mainProvider.retrieveAccessToken(mainConsumer, oAuthVerifier);
            } catch (OAuthMessageSignerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OAuthNotAuthorizedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        /* (non-Javadoc)
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            //super.onPostExecute(result);
            showToken();
        }

    }

    public void setVerifier(String verifier)
    {
        this.oAuthVerifier = verifier;
//      this.webview.loadData("verifier = " + this.OAuthVerifier + "<br>", "text/html", null);
        Log.d("setVerifier", verifier);

        this.showToken();
    }

    public void showToken()
    {
        //Log.d("SubPlurkV2", "Token = " + mainConsumer.getToken() + " and secret = " + mainConsumer.getTokenSecret());
        String str = 
                "verifier = " + this.oAuthVerifier + "<br>" + 
                "Token = " + mainConsumer.getToken() + "<br>" + 
                "secret = " + mainConsumer.getTokenSecret() + "<br>" + 
                "oauth_expires_in = " + mainProvider.getResponseParameters().getFirst("oauth_expires_in") + "<br>" +
                "oauth_session_handle = " + mainProvider.getResponseParameters().getFirst("oauth_session_handle") + "<br>" +
                "oauth_authorization_expires_in = " + mainProvider.getResponseParameters().getFirst("oauth_authorization_expires_in") + "<br>" + 
                "xoauth_yahoo_guid = " + mainProvider.getResponseParameters().getFirst("xoauth_yahoo_guid") + "<br>";
        Log.i("YahooScreen", "str : " + str);
    }

    private void doGet(String url) {
        OAuthConsumer consumer = this.mainConsumer;

        final HttpGet request = new HttpGet(url);
        Log.i("doGet","Requesting URL : " + url);
        try {
            consumer.sign(request);
            Log.i("YahooScreen", "request url : " + request.getURI());
            new Thread(new Runnable() {

                @Override
                public void run() {
                    DefaultHttpClient httpclient = new DefaultHttpClient();
                    HttpResponse response;
                    try {
                        response = httpclient.execute((HttpUriRequest) request);
                        Log.i("doGet","Statusline : " + response.getStatusLine());
                        InputStream data = response.getEntity().getContent();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(data));
                        String responeLine;
                        StringBuilder responseBuilder = new StringBuilder();
                        while ((responeLine = bufferedReader.readLine()) != null) {
                            responseBuilder.append(responeLine);
                        }
                        Log.i("doGet","Response : " + responseBuilder.toString());
                        //return responseBuilder.toString();
                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }).start();

        } catch (OAuthMessageSignerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void getGUID()
    {
        String GUID_URL="http://social.yahooapis.com/v1/me/guid?format=json"; 
        this.doGet(GUID_URL);
    }

    public void getProfile()
    {
        String guid = mainProvider.getResponseParameters().getFirst("xoauth_yahoo_guid");
        String url = "https://social.yahooapis.com/v1/user/" + guid + "/profile?format=json";
        this.doGet(url);
    }
}
like image 55
Wendell Avatar answered Feb 15 '23 09:02

Wendell