200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > android 新浪微博Oauth认证

android 新浪微博Oauth认证

时间:2019-05-02 16:50:34

相关推荐

android 新浪微博Oauth认证

对于新浪微博这块一直很纠结,auth认证让人吐血。之前项目用到的都是copy别人的,最近想详细了解下,就简单实现一二,以便以后自己更好的运用.

准别好以下常量

public String consumerKey = "2803926882";// keypublic String consumerSecret = "d41e6f2d605bd16c785879032ec431f5";// Secret// 自定义回调URL(这个url要在配置文件中配置,)public static final String CALLBACK_URL = "jjhappyforever://WeiboListActivity";// requestTokenURLprivate final String requestTokenEndpointUrl = "http://api./oauth/request_token";// accessTokenURLprivate final String accessTokenEndpointUrl = "http://api./oauth/access_token";// 授权private final String authorizationWebsiteUrl = "http://api./oauth/authorize";

下面两个方法是Oauth.java中的两个方法.

// 获取auth地址public String RetrieveAuthUrl() throws OAuthMessageSignerException,OAuthNotAuthorizedException, OAuthExpectationFailedException,OAuthCommunicationException {authConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);authProvider = new CommonsHttpOAuthProvider(requestTokenEndpointUrl,accessTokenEndpointUrl, authorizationWebsiteUrl);return authProvider.retrieveRequestToken(authConsumer, CALLBACK_URL);}//这个方法是获取用户的 userId,token,tokenSecret等信息.public User getAccessToken(String authUrl)throws OAuthMessageSignerException, OAuthNotAuthorizedException,OAuthExpectationFailedException, OAuthCommunicationException {Log.i(TAG, authUrl);authProvider.setOAuth10a(true);authProvider.retrieveAccessToken(authConsumer, authUrl);User user = new User();user.userId = authProvider.getResponseParameters().getFirst("user_id");user.token = authConsumer.getToken();user.tokenSecret = authConsumer.getTokenSecret();return user;}

在Activity中调用. // 获取authUrl地址String authUrl = oauth.RetrieveAuthUrl();// 启动访问新浪认证页面startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));这样就会执行web 认证在本activity中实现onNewIntent方法,用来执行认证回调后的动作,protected void onNewIntent(Intent intent) {super.onNewIntent(intent);Uri uri = intent.getData();String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);try {User user = null;user = oauth.getAccessToken(verifier);Log.i(Oauth.TAG, user.toString());} catch (OAuthMessageSignerException ex) {ex.printStackTrace();} catch (OAuthNotAuthorizedException ex) {ex.printStackTrace();} catch (OAuthExpectationFailedException ex) {ex.printStackTrace();} catch (OAuthCommunicationException ex) {ex.printStackTrace();}}在这里要说一下配置文件中的配置:<activityandroid:name=".TestActivity"android:launchMode="singleInstance" ><!-—— 这个lanchMode模式一定要设置,不设置的话会一直执行oncreate. 不会执行onNewIntent 我在这里纠结好久.——><intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><dataandroid:host="Oauth"android:scheme="jjhappyforevert" /></intent-filter></activity>到这里就实现了Oauth认证流程.下一篇,要简单介绍下根据开放平台API如果调用用户的微博信息.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。