接着上一篇文章"使用WebView实现新浪微博OAuth登录",实现腾讯微博OAuth登录。
#腾讯官方下载SDK
http://open.t.qq.com/resource.php?i=3,1
#申请应用KEY
登录腾讯微博,进入http://open.t.qq.com/申请应用,获取KEY和SECRET。
#准备
在项目中导入QWeiboSDK.jar、dom4j-1.6.1.jar(这两个包是由官方下载的SDK提供)
这里只给出腾讯OAuth登录代码,其它代码看上一篇文章
package com.oauth;
import com.db.DbHelper;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class TencentOAuth extends OAuthActivity {
public static final String CONSUMER_KEY = "应用KEY";
public static final String CONSUMER_SECRET = "应用SECRET";
private OAuthClient oauthClient;
private OAuth oauth;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
titleView.setText("腾讯微博登录");
}
@Override
protected void oauthLogin() {
oauth = new OAuth(CONSUMER_KEY, CONSUMER_SECRET, "weibo4android://CallbackActivity");
oauthClient = new OAuthClient();
try {
oauthClient.requestToken(oauth);
String authUrl = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="+oauth.getOauth_token();
oauthWebView.loadUrl(authUrl);//自定义WebView
} catch (Exception e) {
e.printStackTrace();
}
oauthActivity = this;//此处很关键
}
@Override
protected void callback(Intent callbackIntent) {
Uri uri = callbackIntent.getData();
oauth.setOauth_verifier(uri.getQueryParameter("oauth_verifier"));
try {
oauthClient.accessToken(oauth);
} catch (Exception e) {
e.printStackTrace();
}
DbHelper.persistUser(Share.TENCENT, 0, oauth.getOauth_token(), oauth.getOauth_token_secret());
Intent intent = getIntent();
intent.putExtra("oauth_type", Share.TENCENT);
intent.putExtra("token", oauth.getOauth_token());
intent.putExtra("secret", oauth.getOauth_token_secret());
intent.setClass(TencentOAuth.this, ShareActivity.class);
this.startActivity(intent);
this.finish();
}
}