微博 Android 平台 SDK 为第三方应用提供了简单易用的微博API调用服务,使第三方客户端无需了解复杂的验证机制即可进行授权登陆,并提供微博分享功能,可直接通过微博官方客户端分享微博。

Android 实现新浪微博第三方登录方法,具体步骤如下:

1.下载微博 SDK,下载地址http://open.weibo.com/wiki/SDK#Android_SDK ,导入微博 jar包 android-support-v4.jar 和 weibosdkcore.jar

2.从 github 中下载新浪微博demo_src,把demo包的 SDK 导入项目中

3.将 demo 中的constants 参数设置为申请的新浪微博给出的相关参数

4.新浪微博 SDK 中有 Demo 演示如何通过 oauth认证,认证和使用流程如下:

1)在/weibo4android/src/weibo4android/Weibo.java 设置App Key 和App Secret ,获取地址 http://open.weibo.com/webmaster/info/basic?siteid=1650065615,具体代码如下:

public static String CONSUMER_KEY = "xxxxxxxx";
public static String CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxx";

2)在/weibo4android/examples/weibo4android/androidexamples/AndroidExample.java中,使用App Key 和App Secret参数,具体代码如下:

System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);

3)通过http post方式向服务提供方请求获得RequestToken,参数 "weibo4android://OAuthActivity" 为回调URL,即用户对第三方应用授权后会通过此URL返回第三方应用, 回调URL作为请求参数传递给服务提供方,具体代码如下:

RequestToken  requestToken = weibo.getOAuthRequestToken("weibo4android://OAuthActivity");

4)将用户引导至新浪微博授权页面,具体代码如下:

Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&display=mobile");
startActivity(new Intent(Intent.ACTION_VIEW, uri));

5)授权页面要求用户输入用户名和密码授权完成之后,服务端会通过回调URL将用户引导至客户端 OAuthActivity 页面,具体代码如下:

<activity android:name=".OAuthActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="weibo4android" android:host="OAuthActivity" /> 
    </intent-filter>
</activity>

6)客户端根据临时令牌和用户 oauth_verifier 授权码从服务端获取访问 Access Token,具体代码如下:

Uri uri=this.getIntent().getData();
RequestToken requestToken= OAuthConstant.getInstance().getRequestToken();
AccessToken  accessToken=requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));

7)获得 Access Token 后使用API接口获得用户信息,具体代码如下:

Weibo weibo=OAuthConstant.getInstance().getWeibo();
weibo.setToken(OAuthConstant.getInstance().getToken(), OAuthConstant.getInstance().getTokenSecret());
String[] args = new String[2];
args[0]=OAuthConstant.getInstance().getToken();
args[1]=OAuthConstant.getInstance().getTokenSecret();
try {
    GetFollowers.main(args);
} catch (Exception e) {
    e.printStackTrace();
}
你可能感兴趣的内容
Android中远程Service浅析 收藏,4243 浏览
0条评论

dexcoder

这家伙太懒了 <( ̄ ﹌  ̄)>
Owner