android腾讯微博Oauth2.0认证以及登录

之前发表过博文说明了如何使用基于OAUTH2.0新浪微博认证以及登陆

链接如下:http://blog.csdn.net/geniuseoe2012/article/details/7727564

 

今天也来侃侃如何使用基于OAUTH2.0的腾讯微博认证以及登陆

网上其实也有不少例子,但很多都是基于OAUTH1.0的认证

然后SDK包会有很多显得异常臃肿,有些童鞋并不是做的腾讯微博客户端之类的软件

而只是需要用到其分享到腾讯微博的小功能而已,那么导入如此之多的jar包实在是没有必要

而且官方出了2.0的认证,对SDK也作了很多精简,我们自然也要与时俱进了

故此小编特地研究了下官方API文档和DEMO,在SDK基础上作了简单封装方便童鞋们使用

 

这里对于如何开发腾讯微博的基础知识就不作普及了,大家看官方文档就OK了

http://wiki.open.t.qq.com/index.php/%E7%A7%BB%E5%8A%A8%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5/Android_SDK_V1.2

 

下面上几张效果图:

android腾讯微博Oauth2.0认证以及登录_第1张图片

android腾讯微博Oauth2.0认证以及登录_第2张图片

android腾讯微博Oauth2.0认证以及登录_第3张图片

 

其实不同微博它们的认证过程都是大同小异

我们在认证页面认证通过后需要获得三个值:

access_token  授权码

openid              用户统一标识 ,可以唯一标识一个用户      

openkey          与openid对应的用户key,是验证openid身份的验证密钥

 

得到这三个值后将其保存到数据库,下次再进入应用的时候,将其设入OAuthV2即可(本例采用2.0认证,故接口调用均涉及到此类)

先看看webview认证页面代码:

public class OAuthV2WebViewActivity extends Activity {
	
	private final CommonLog log = LogFactory.createLog();

	private View progressBar;
	
	
    private Context mContext;
    private WebView mWebView;
    private WebViewClient mWebViewClient;
    private QQWeiboProxy mQqWeiboProxy;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.webview_layout);
        mContext = this;
        
        initView();
       
        initData();
      
       
    }
    
    
    private void initView()
    {
    	mWebView = (WebView) findViewById(R.id.webview);
	    mWebView.setVerticalScrollBarEnabled(false);
	    mWebView.setHorizontalScrollBarEnabled(false);
	    mWebView.requestFocus();
	    
	    WebSettings webSettings = mWebView.getSettings();
	    webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setSupportZoom(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		
		progressBar = findViewById(R.id.show_request_progress_bar);
    }
    
    private void initData()
    {
    	mWebViewClient = new WeiboWebViewClient();
		mWebView.setWebViewClient(mWebViewClient);
		
		CookieSyncManager.createInstance(this);
		 
		mQqWeiboProxy = QQWeiboProxy.getInstance();
        String urlStr = mQqWeiboProxy.getAuthoUrl();

        mWebView.requestFocus();
        mWebView.loadUrl(urlStr);
    }
    
    private void showProgress()
	{
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressBar.setVisibility(View.VISIBLE);
			}
		});
		
	}
	
	private void hideProgress()
	{
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressBar.setVisibility(View.INVISIBLE);
			}
		});


	}

	
	 private class WeiboWebViewClient extends WebViewClient
	 {
		 @Override
         public void onPageStarted(WebView view, String url, Bitmap favicon) {
        	 showProgress();
        	 log.e("onPageStarted	URL = " + url);
             if (url.indexOf("access_token=") != -1) {
                 int start=url.indexOf("access_token=");
                 String responseData=url.substring(start);
                
                 boolean ret = mQqWeiboProxy.parseAccessTokenAndOpenId(responseData);
                 if (ret)
                 {
                 	String access_token = mQqWeiboProxy.getAccessToken();
                 	String expires_in = mQqWeiboProxy.getExpireIn();
                 	String openID = mQqWeiboProxy.getOpenID();
                 	String openKey = mQqWeiboProxy.getOpenKey();
                 	 
         	        log.e("access_token = " + access_token + "\nexpires_in = " + expires_in + 
         	        		"\nopenID = " + openID + "\nopenKey = " + openKey);

         			AuthoSharePreference.putToken(mContext, access_token);
         			AuthoSharePreference.putExpires(mContext, expires_in);
         			AuthoSharePreference.putOpenID(mContext, openID);		  
         			AuthoSharePreference.putOpenKey(mContext, openKey);
         			            			
                    setResult(RESULT_OK);
                 	finish();
                 }else{
                 	Toast.makeText(OAuthV2WebViewActivity.this, "Autho Fail...", Toast.LENGTH_SHORT).show();
                 }
           
                 view.destroyDrawingCache();
                 view.destroy();
               
             }
             super.onPageStarted(view, url, favicon);
         }
         
         

         @Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
        	hideProgress();
			super.onPageFinished(view, url);
		}


		/*
          * TODO Android2.2及以上版本才能使用该方法 
          * 目前https://open.t.qq.com中存在http资源会引起sslerror,待网站修正后可去掉该方法
          */
         public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
             if ((null != view.getUrl()) && (view.getUrl().startsWith("https://open.t.qq.com"))) {
                 handler.proceed();// 接受证书
             } else {
                 handler.cancel(); // 默认的处理方式,WebView变成空白页
             }
             // handleMessage(Message msg); 其他处理
         }
	 }
}

 

 boolean ret = mQqWeiboProxy.parseAccessTokenAndOpenId(responseData);

用于解析url得到各项值

public boolean parseAccessTokenAndOpenId(String data)
	{
		if (data != null)
		{
			return OAuthV2Client.parseAccessTokenAndOpenId(data, mAuthV2);
		}
		
		return false;
	}

 

然后将其存入数据库

String access_token = mQqWeiboProxy.getAccessToken();
                 	String expires_in = mQqWeiboProxy.getExpireIn();
                 	String openID = mQqWeiboProxy.getOpenID();
                 	String openKey = mQqWeiboProxy.getOpenKey();
                 	 
         	        log.e("access_token = " + access_token + "\nexpires_in = " + expires_in + 
         	        		"\nopenID = " + openID + "\nopenKey = " + openKey);

         			AuthoSharePreference.putToken(mContext, access_token);
         			AuthoSharePreference.putExpires(mContext, expires_in);
         			AuthoSharePreference.putOpenID(mContext, openID);		  
         			AuthoSharePreference.putOpenKey(mContext, openKey);


 

在测试微博API界面调用如下:

public class TestAPIActivity extends Activity implements OnClickListener{

private final CommonLog log = LogFactory.createLog();
	
	
	private Button mBtnGetUserinfo;	
	private Button mBtnSendWeibo;
	private TextView mTvInfo;

	private QQWeiboProxy mQqWeiboProxy;
	
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_layout);
        
        initView();

        initData();
    }
	    
	
   
   public void initView()
   {
	   mBtnGetUserinfo = (Button) findViewById(R.id.btn_getuser);
	   mBtnGetUserinfo.setOnClickListener(this);

	   mBtnSendWeibo = (Button) findViewById(R.id.btn_sendweibo);
	   mBtnSendWeibo.setOnClickListener(this);
	 
	   mTvInfo = (TextView) findViewById(R.id.tv_info);
   }
   
   public void initData()
   {
	   mQqWeiboProxy = QQWeiboProxy.getInstance();
	   
   }

   private void showInfo(String str)
   {
	   if (str != null)
	   {
		   mTvInfo.setText(str);
	   }else{
		   mTvInfo.setText("null");
	   }
   }

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch(view.getId())
		{
		case R.id.btn_getuser:
			getUser();
			break;
		case R.id.btn_sendweibo:
			sendWeibo();
			break;
		}
	}

	private void getUser()
	{
		String jString = mQqWeiboProxy.getUserInfo();
		showInfo(jString);
	}
	
	private void sendWeibo()
	{
		String jString = mQqWeiboProxy.sendWeibo("geniuseoe2012");
		showInfo(jString);
	}


 

QQWeiboProxy是对SDK的封装类

public class QQWeiboProxy {

	/*
	 * 请将以下三个参数替换成自己的应用值
	 */
	public final static String CONSUMER_KEY = "";				// appkey		
	public final static String CONSUMER_SECRET = "";			// secret		
	public final static String REDIRECT_URL = ""; 				// url回调地址
	

	
	private final CommonLog log = LogFactory.createLog();
	
	private final static String FORMAT = "json";
	private final static String CLIENT_IP = "127.0.0.1";
	
	
	private OAuthV2 mAuthV2;

	private static QQWeiboProxy mWeiboManager;
	
	
	public static synchronized QQWeiboProxy getInstance()
	{
		if (mWeiboManager == null)
		{
			mWeiboManager = new QQWeiboProxy();
		}
		
		return mWeiboManager;
	}
	
	
	private QQWeiboProxy()
	{		
		
		mAuthV2 = new OAuthV2(REDIRECT_URL);
		mAuthV2.setClientId(CONSUMER_KEY);
		mAuthV2.setClientSecret(CONSUMER_SECRET);
		
	
	}
		
	public String getRedictUrl()
	{
		return REDIRECT_URL;
	}
	
	public String getAppKey()
	{
		return CONSUMER_KEY;
	}
	

	// 		 获得AUTHO认证URL地址
	public  String getAuthoUrl()
	{
	    
	    String urlStr = OAuthV2Client.generateImplicitGrantUrl(mAuthV2);
	    
	    return urlStr;
	}
	
	public void setAccesToakenString(String token)
	{
		if (token != null)
		{
			 mAuthV2.setAccessToken(token);
		}
		
	}
	
	public void setOpenid(String openID)
	{
		if (openID != null)
		{
			mAuthV2.setOpenid(openID);
		}
	}
	
	public void setOpenKey(String openKey)
	{
		if (openKey != null)
		{
			mAuthV2.setOpenkey(openKey);
		}
	}
	
	public void setExpireIn(String expireIn)
	{
		if (expireIn != null)
		{
			mAuthV2.setExpiresIn(expireIn);
		}
	}
	
	
	public boolean parseAccessTokenAndOpenId(String data)
	{
		if (data != null)
		{
			return OAuthV2Client.parseAccessTokenAndOpenId(data, mAuthV2);
		}
		
		return false;
	}
	
	public String getAccessToken()
	{
		return mAuthV2.getAccessToken();
	}
	
	public String getOpenID()
	{
		return mAuthV2.getOpenid();
	}
	
	public String getOpenKey()
	{
		return mAuthV2.getOpenkey();
		
	}
	
	public String getExpireIn()
	{
		return mAuthV2.getExpiresIn();
	}
	
	
	// 获取用户资料
	public String getUserInfo()
	{
		String reString = null;
		UserAPI mUserAPI = new UserAPI(OAuthConstants.OAUTH_VERSION_2_A);
		try {
			
			reString = mUserAPI.info(mAuthV2, FORMAT);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		mUserAPI.shutdownConnection();
		
		return reString;
	}
	
	// 发送微博
	public String sendWeibo(String content)
	{
		String rString = null;
		TAPI mTapi = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
		try {
			
			rString = mTapi.add(mAuthV2, FORMAT, content, CLIENT_IP);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mTapi.shutdownConnection();
		
		return rString;
	}
	
}


测试下发微博,调用得到的json串显示在屏幕上,登陆微博查看发送成功!

 

下面简单介绍下工程代码:

android腾讯微博Oauth2.0认证以及登录_第4张图片

 

com.mobile.tencent.weibo.sdk包是官方SDK源码拷贝过来的(作了部分裁剪)

com.mobile.tencent.weibo.sdk.proxy里除了QQWeiboProxy其它的也是SDK的源码,那些API后缀类已经封装了很多接口了

唯一额外需要导入的就一个httpmime-4.1.3jar包

 

这样童鞋们就可以很方便滴将代码COPY走而应用到自己的项目,当然也可以选择将那些代码重新打一个jar包导入工程

差不多就这样啦,附上工程链接:

http://download.csdn.net/detail/geniuseoe2012/4565412

 最后大家记得要更换自己的应用KEY值


以后会陆续更新完整的客户端源码,敬请留意窝的博客更新

你可能感兴趣的:(android,String,腾讯,Access,token,redirect)