【Android 腾讯微博】-- Oauth2.0认证以及登录

来源:互联网 发布:筹码分布指标源码 编辑:程序博客网 时间:2024/04/29 03:51


申请AppKey,AppSecret

必须到微博开放平台官方网站申请应用的AppKey和AppSecret后,才能完成微博登录。

SDK(Android_SDK_v1.2.jar)适用的开发环境

  • JAVA SDK v5 及以上
  • Android SDK 2.2(level8) 及以上
  • 依赖包:httpmime-4.1.3.jar

特别说明: Android SDK 2.2以下版本的Webview不提供处理SSL异常的方法,因此,如需在Andriod2.2以下版本开发应用,请使用修改版SDK(Android_SDK_v1.2_Fix.jar,该版本只能使用OAuth1.0授权和调用1.0 API,所有连接均为普通http连接)

SDK使用方法

修改AndroidManifest.xml文件

  • 在<manifest>标签中,添加:
<!-- 允许网络访问 --><uses-permission android:name="android.permission.INTERNET" />
  • 在<application>标签中,添加:
<!-- OAuth Version 2. 使用  WebView 辅助进行ImplicitGrant方式授权必须 --><activity    android:name="com.tencent.weibo.webview.OAuthV2AuthorizeWebView"    android:label="@string/app_name" ></activity>

添加必要JAR包

Android_SDK_v1.2.jar 和 httpmime-4.1.3.jar


-----------------------以上为官方说明-----------------------

认证很简单,官方直接给出了代码,

public class OauthActivity extends Activity{ private OAuthV2 oAuth;        public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.oauth);        oAuth=new OAuthV2("http://www.tencent.com/zh-cn/index.shtml"); // url回调地址        oAuth.setClientId("801**5505"); // appkey        oAuth.setClientSecret("be1dd1410434a9f7d5a2586b****6829"); // secret        Intent intent = new Intent(OauthActivity.this, OAuthV2AuthorizeWebView.class);        intent.putExtra("oauth", oAuth);        startActivityForResult(intent,1);       }        protected void onActivityResult(int requestCode, int resultCode, Intent data)   {        if (requestCode==1) {            if (resultCode==OAuthV2AuthorizeWebView.RESULT_CODE)    {                oAuth=(OAuthV2) data.getExtras().getSerializable("oauth");                //调用API获取用户信息                UserAPI userAPI=new UserAPI(OAuthConstants.OAUTH_VERSION_2_A);                try {                    String response=userAPI.info(oAuth, "json");//获取用户信息                    ((TextView)findViewById(R.id.textView)).setText(response+"\n");                } catch (Exception e) {                    e.printStackTrace();                }                userAPI.shutdownConnection();                            }        }    }}