独角兽企业重金招聘Python工程师标准>>>
1.通过官方网址下载SDK:
Weibo4Android:
/p/weibo4j/downloads/detail?name=weibo4android-1.2.1.zip
2.SDK中有现成的Demo演示如何通过oauth认证,认证和使用流程大概如下:
(1)在/weibo4android/src/weibo4android/Weibo.java 设置App Key 和App Secret(在官方网站新建应用可获得) ,如下所示:
public static String CONSUMER_KEY = "2664209963";public static String CONSUMER_SECRET = "b428615797a5d676d428cd146c040399";
(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
RequestToken requestToken =weibo.getOAuthRequestToken("weibo4android://OAuthActivity");
("weibo4android://OAuthActivity" 为回调URL,即用户对第三方应用授权后会通过此URL返回第三方应用, 回调URL作为请求参数传递给服务提供方)
(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)客户端根据临时令牌和用户授权码从服务提供方那里获取访问令牌 (Access Token)
Uri uri=this.getIntent().getData();RequestToken requestToken= OAuthConstant.getInstance().getRequestToken();AccessToken accessToken=requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
uri.getQueryParameter("oauth_verifier")为用户授权后返回的授权码
(7)获得访问令牌后便可使用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();}