我的应用需要获取用户的聚会ID。 Meetup使用oauth 2.0。在网络上找到不同的代码段,将粘贴到stackoverflow中作为下一个问题的答案。

最佳答案

通过gradle构建文件导入库:

dependencies {
    compile 'net.smartam.leeloo:oauth2-common:0.1'
    compile 'net.smartam.leeloo:oauth2-client:0.1'
}


创建一个用于聚会验证的类。这个由adrianmaurer(https://gist.github.com/adrianmaurer/4673944)编写的课程,谢谢adrianmaurer!

MeetupAuthActivity:

package pixtas.com.nightout;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

// leeloo oAuth lib https://bitbucket.org/smartproject/oauth-2.0/wiki/Home
import net.smartam.leeloo.client.OAuthClient;
import net.smartam.leeloo.client.URLConnectionClient;
import net.smartam.leeloo.client.request.OAuthClientRequest;
import net.smartam.leeloo.client.response.OAuthAccessTokenResponse;
import net.smartam.leeloo.client.response.OAuthAuthzResponse;
import net.smartam.leeloo.common.exception.OAuthProblemException;
import net.smartam.leeloo.common.exception.OAuthSystemException;
import net.smartam.leeloo.common.message.types.GrantType;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

/**
 * Created by tmr_byronMac on 4/24/15.
 */
public class MeetupAuthActivity  extends Activity {
    private final String TAG = getClass().getName();

    // Meetup OAuth Endpoints
    public static final String AUTH_URL = "https://secure.meetup.com/oauth2/authorize";
    public static final String TOKEN_URL = "https://secure.meetup.com/oauth2/access";

    //     Consumer
    //public static final String REDIRECT_URI_SCHEME = "oauthresponse";
    //public static final String REDIRECT_URI_HOST = "com.yourpackage.app";
    //public static final String REDIRECT_URI_HOST_APP = "yourapp";
    //public static final String REDIRECT_URI = REDIRECT_URI_SCHEME + "://" + REDIRECT_URI_HOST + "/";
    public static final String REDIRECT_URI = "NightOut://meetup.com";
    public static final String CONSUMER_KEY = "YOUR_KEY";
    public static final String CONSUMER_SECRET = "YOUR_SECRET";

    private WebView _webview;
    private Intent _intent;
    private Context _context;

    public void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        _intent = getIntent();
        _context = getApplicationContext();

        _webview = new WebView(this);
        _webview.setWebViewClient(new MyWebViewClient());
        setContentView(_webview);

        _webview.getSettings().setJavaScriptEnabled(true);
        OAuthClientRequest request = null;
        try {
            request = OAuthClientRequest.authorizationLocation(
                    AUTH_URL).setClientId(
                    CONSUMER_KEY).setRedirectURI(
                    REDIRECT_URI).buildQueryMessage();
        } catch (OAuthSystemException e) {
            Log.d(TAG, "OAuth request failed", e);
        }
        _webview.loadUrl(request.getLocationUri() + "&response_type=code&set_mobile=on");
    }

    public void finishActivity() {
        //do something here before finishing if needed
        finish();
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);

            String code = uri.getQueryParameter("code");
            String error = uri.getQueryParameter("error");

            if (code != null) {
                new MeetupRetrieveAccessTokenTask().execute(uri);

                // setResult(RESULT_OK, _intent);
                // finishActivity();
            } else if (error != null) {
                setResult(RESULT_CANCELED, _intent);
                finishActivity();
            }
            return false;
        }
    }

    private class MeetupRetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {

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

            Uri uri = params[0];
            String code = uri.getQueryParameter("code");

            OAuthClientRequest request = null;

            try {
                request = OAuthClientRequest.tokenLocation(TOKEN_URL)
                        .setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(
                                CONSUMER_KEY).setClientSecret(
                                CONSUMER_SECRET).setRedirectURI(
                                REDIRECT_URI).setCode(code)
                        .buildBodyMessage();

                OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

                OAuthAccessTokenResponse response = oAuthClient.accessToken(request);

                // do something with these like add them to _intent
                // Intent returnIntent = new Intent();
                // returnIntent.putExtra("access_token", response.getAccessToken());
                // setResult(RESULT_OK,returnIntent);


                Log.d(TAG, "access token: " + response.getAccessToken());
                Log.d(TAG, response.getExpiresIn());
                Log.d(TAG, response.getRefreshToken());

                _intent.putExtra("access_token", response.getAccessToken());
                setResult(RESULT_OK, _intent);
                finish();
            } catch (OAuthSystemException e) {
                Log.e(TAG, "OAuth System Exception - Couldn't get access token: " + e.toString());
                Toast.makeText(_context, "OAuth System Exception - Couldn't get access token: " + e.toString(), Toast.LENGTH_LONG).show();
            } catch (OAuthProblemException e) {
                Log.e(TAG, "OAuth Problem Exception - Couldn't get access token");
                Toast.makeText(_context, "OAuth Problem Exception - Couldn't get access token", Toast.LENGTH_LONG).show();
            }
            return null;
        }
    }

    @Override
    public void onBackPressed()
    {
        setResult(RESULT_CANCELED, _intent);
        finishActivity();
    }
}


从您的主要活动中致电MeetupAuthActivity。
主要活动:

public void getMeetupAccessToken(){
    Intent intent;
    intent = new Intent(this, MeetupAuthActivity.class);
    // startActivity(intent);
    startActivityForResult(intent,GET_MEETUP_ACCESS_TOKEN_ACTIVITY);
}


在MainActivity中,从auth活动捕获结果。
主要活动:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // if(requestCode == 1 && resultCode == RESULT_OK)
        if(requestCode == GET_MEETUP_ACCESS_TOKEN_ACTIVITY)
        {
            accessToken = data.getExtras().getString("access_token");
            saveMeetupAccessTokenToSharedPreferences();

            //save meetupid plus device id to parse
            getMyMeetupIdFromMeetupServer();

            // Log.i(DEBUG_TAG,"MainActivity, accessToken" + accessToken);
        }
    }

10-08 17:29