首页 > 安全资讯 >

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

12-09-13

下面上几张效果图:其实不同微博它们的认证过程都是大同小异我们在认证页面认证通过后需要获得三个值:access_token 授权码openid 用户统一标识 ,可以唯一标识一个用户openkey 与openid对应的用户key,是验...

下面上几张效果图:

 

 

 

 

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

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

access_token  授权码

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

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

 

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

先看看webview认证页面代码:

[java]
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得到各项值

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

然后将其存入数据库

[java] 
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界面调用如下:

[java]
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的封装类

[java] 
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串显示在屏幕上,登陆微博查看发送成功!

 

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

 

 

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

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

相关文章
最新文章
热点推荐