Sina Weibo SSO login mode and OAUTH2.0 certification and access to my Weibo

Source: Internet
Author: User
Tags parse string

Today I got the Sina Weibo SSO login mode and OAUTH2.0 certification and get my Weibo, the effect of the implementation is as follows:


//============================================================================================================= =============

Just so simple interface, simple request JSON, I actually got a whole day, mainly Sina Weibo documents written to understand, feel their documents and their SDK can not connect.

One of the problems encountered is:

SSO package or sign error----

The workaround is to:

Using the MD5 signature apk that they provide, enter the package name to generate the MD5 value, output to the open platform can be resolved. (My qq:619189810)

All the code:

Layout:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" > <button android:id= "@+id/obtain_token_via_sso" Android:layout_width= "mat Ch_parent "android:layout_height=" wrap_content "android:gravity=" left|center_vertical "android:text="        SSO Authorization (client only) "/> <button android:id=" @+id/logout "android:layout_width=" Match_parent " android:layout_height= "Wrap_content" android:layout_margintop= "10DP" android:gravity= "Left|center_vertica L "android:text=" user log Out "/> <textview android:layout_width=" Wrap_content "Androi d:layout_height= "Wrap_content" android:layout_margintop= "10DP" android:textsize= "16SP" android:textst Yle= "Bold" android:text= "Token info:"/> <textview android:id= "@+id/token_text_view" android:layout_width= "Fill_parent" Android:layout_heig ht= "Wrap_content" android:textsize= "12sp"/> <button android:id= "@+id/sys" Android:layout_w Idth= "Match_parent" android:layout_height= "wrap_content" android:layout_margintop= "10DP" android:onCl ick= "click" android:gravity= "left|center_vertical" android:text= "I'm interested in Weibo"/> <scrollview android: Layout_width= "Match_parent" android:layout_height= "wrap_content" > <linearlayout android:or ientation= "vertical" android:id= "@+id/word" android:layout_width= "Match_parent" android:layout_he ight= "Match_parent"/> </ScrollView> </LinearLayout>

Mainactivity:

Package Yuan.duo.ustc.sinaclient;import Java.text.simpledateformat;import Java.util.arraylist;import Java.util.list;import Android.app.activity;import Android.content.intent;import Android.os.Bundle;import Android.text.textutils;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.linearlayout;import Android.widget.textview;import Android.widget.toast;import Com.sina.weibo.sdk.auth.authinfo;import Com.sina.weibo.sdk.auth.oauth2accesstoken;import Com.sina.weibo.sdk.auth.weiboauthlistener;import Com.sina.weibo.sdk.auth.sso.ssohandler;import Com.sina.weibo.sdk.exception.weiboexception;import Com.sina.weibo.sdk.net.requestlistener;import Com.sina.weibo.sdk.net.weiboparameters;import Com.sina.weibo.sdk.openapi.statusesapi;import Com.sina.weibo.sdk.openapi.models.errorinfo;import Com.sina.weibo.sdk.openapi.models.status;import Com.sina.weibo.sdk.openapi.models.statuslist;import Com.sina.weibo.sdk.utils.logutil;public class MainActivity Extends Activity {Protected static final String TAG = "mainactivity";p rivate AuthInfo mauthinfo;private TextView mtokentext;private Ssohandler Mssohandler;private weiboparameters parameters;/** encapsulates "Access_token", "expires_in", "Refresh_token", and provides their management functions */ Private Oauth2accesstoken maccesstoken;/** API */private Statusesapi mstatusesapi;private LinearLayout for operations such as microblogging information flow Word; @Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); word = (linearlayout) Findviewbyid (R.id.word);//Get current saved Tokenmaccesstoken = Accesstokenkeeper.readaccesstoken (this);//Statusapi instantiation Mstatusesapi = new Statusesapi (this, Constants.app_key, Maccesstoken); mauthinfo = new AuthInfo (this, Constants.app_key,constants.redirect_url, constants.scope); mTokenText = (TextView) Findviewbyid (r.id.token_text_view); mssohandler = new Ssohandler (mainactivity.this, mauthinfo); Findviewbyid (R.id.obtain_token_via_sso). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {mssohandler.authorize (New Authlistener ());}}); Findviewbyid (r.id.logout). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) { Accesstokenkeeper.clear (Getapplicationcontext ()); Maccesstoken = new Oauth2accesstoken (); Updatetokenview (false);}}); /Read the Last saved good Accesstoken information from sharedpreferences,//Start the application for the first time, Accesstoken not available Maccesstoken = Accesstokenkeeper.readaccesstoken (this), if (Maccesstoken.issessionvalid ()) {Updatetokenview (true);}} /** * This function is called when SSO authorization Activity exits. * * @see {@link Activity#onactivityresult} */@Overrideprotected void onactivityresult (int requestcode, int resultcode, in Tent data) {Super.onactivityresult (Requestcode, ResultCode, data);//SSO authorization callback//IMPORTANT: Activity that initiates SSO login must be rewritten Onactivityresu Ltif (Mssohandler! = null) {Mssohandler.authorizecallback (Requestcode, ResultCode, data);}} /** * Weibo authentication authorization callback class. 1. When SSO is granted, the callback will not be executed until {@link Ssohandler#authorizecallback} is called in {@link #onActivityResult}. 2. When a non-SSO * is authorized, the callback is executed when the authorization is completed. WhenAfter the authorization is successful, please save the Access_token, expires_in, UID and other information into the * sharedpreferences. */class Authlistener implements Weiboauthlistener {@Overridepublic void OnCancel () {Toast.maketext (Mainactivity.this, "Authorization Cancellation", Toast.length_long). Show ();} @Overridepublic void OnComplete (Bundle values) {//Parse Tokenmaccesstoken = Oauth2accesstoken.parseaccesstoken from bundle ( Values), if (Maccesstoken.issessionvalid ()) {//Display Tokenupdatetokenview (FALSE);//Save Token to Sharedpreferencesaccesstokenkeeper.writeaccesstoken (Mainactivity.this,maccesstoken); Toast.maketext (Mainactivity.this, "Authorization succeeded", Toast.length_short). Show (); else {///In the following cases, you will receive code://1. When you do not register the package name and signature of the application on the platform,//2. When you register an application package name with an incorrect signature;//3. When the package name and signature you registered on the platform do not match the package name and signature of the app you are currently testing String code = values.getstring ("code"); String message = getString (r.string.weibosdk_demo_toast_auth_failed); Textutils.isempty (code)) {message = message + "\nobtained The Code:" + code;} Toast.maketext (mainactivity.this, message, Toast.length_long). Show ();}} @Overridepublic void Onweiboexception (weiboexception e) {toast.maketext (Mainactivity.this, "Auth exception:" + E.getmessage (), Toast.length_long). Show ();}} /** * Displays the current Token information. * * @param hasexisted * The token information is already present in the config file and is valid */private void Updatetokenview (Boolean hasexisted) {String dat E = new SimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"). Format (New Java.util.Date (Maccesstoken.getexpirestime ())); String format = getString (r.string.weibosdk_demo_token_to_string_format_1); Mtokentext.settext (String.Format ( Format, Maccesstoken.gettoken (), date)); String message = String.Format (format, Maccesstoken.gettoken (), date), if (hasexisted) {message = GetString ( r.string.weibosdk_demo_token_has_existed) + "\ n" + message;} Mtokentext.settext (message);} public void Click (View view) {if (Maccesstoken! = null && maccesstoken.issessionvalid ()) { Mstatusesapi.friendstimeline (0L, 0L, 1, False, 0, False,mlistener);}} /** * Weibo OpenAPI callback interface. */private Requestlistener Mlistener = new Requestlistener () {@Overridepublic void OncompletE (String response) {list<status> List = new arraylist<status> (); Textutils.isempty (response)) {logutil.i (TAG, Response), if (Response.startswith ("{\" Statuses\ "")) {//Call statuslist# Parse parse string into microblog list object statuslist statuses = statuslist.parse (response); if (statuses! = null && Statuses.total_ Number > 0) {toast.maketext (Mainactivity.this, "get the Twitter stream successfully, Count:" + statuses.statusList.size (), Toast.length_long). Show (); list = Statuses.statuslist;for (Status status:list) {TextView TV = new TextView (mainactivity.this); Tv.settext (St Atus.text); System.out.println (Status.text); Word.addview (TV);}}} @Overridepublic void Onweiboexception (Weiboexception e) {LOGUTIL.E (TAG, E.getmessage ()); ErrorInfo info = errorinfo.parse (e.getmessage ()); Toast.maketext (Mainactivity.this, info.tostring (), Toast.length_long). Show ();}};}
Constants Interface:

Package Yuan.duo.ustc.sinaclient;public interface Constants {public static final String App_key = "313569838";//Application App_k Eypublic static final String Redirect_url = "https://api.weibo.com/oauth2/default.html"; App callback page public static final String SCOPE =//Application Request Advanced Permissions "Email,direct_messages_read,direct_messages_write," + " Friendships_groups_read,friendships_groups_write,statuses_to_me_read, "+" follow_app_official_microblog, "+" Invitation_write ";  }

Accesstokenkeeper:

Package Yuan.duo.ustc.sinaclient;import Com.sina.weibo.sdk.auth.oauth2accesstoken;import Android.content.Context; Import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;public class Accesstokenkeeper {private static final string preferences_name = "Com_weibo_sdk_android";p rivate static final string KEY _uid = "UID";p rivate static final String key_access_token = "Access_token";p rivate static final String key_expires_in = "E Xpires_in ";p ublic static void Writeaccesstoken (context context, Oauth2accesstoken token) {if (null = = Context | | null = = T Oken) {return;} Sharedpreferences pref = context.getsharedpreferences (preferences_name,context.mode_private); Editor editor = Pref.edit (); editor.putstring (Key_uid, Token.getuid ()); Editor.putstring (Key_access_token, Token.gettoken ()); Editor.putlong (key_expires_in, Token.getexpirestime ()); Editor.commit ();} public static Oauth2accesstoken Readaccesstoken (context context) {if (null = = Context) {return null;} Oauth2accesstoken token = new Oauth2accesstoken (); Sharedpreferences pref = context.getsharedpreferences (preferences_name,context.mode_private); Token.setUid ( Pref.getstring (Key_uid, "")), Token.settoken (Pref.getstring (Key_access_token, "")); Token.setexpirestime ( Pref.getlong (key_expires_in, 0)); return token;} public static void Clear (context context) {if (null = = Context) {return;} Sharedpreferences pref = context.getsharedpreferences (preferences_name,context.mode_append); Editor editor = Pref.edit (); Editor.clear (); Editor.commit ();}}


Manifest file:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Yuan.duo.ustc.sinaclient "android:versioncode=" 1 "android:versionname=" 1.0 "> &LT;USES-SD K android:minsdkversion= "android:targetsdkversion="/> <!--SDK permissions and <uses-perm Ission android:name= "Android.permission.INTERNET"/> <uses-permission android:name= " Android.permission.ACCESS_WIFI_STATE "/> <uses-permission android:name=" android.permission.ACCESS_NETWORK_ State "/> <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/> <!--used to invoke JNI--&    Gt         <uses-permission android:name= "Android.permission.READ_PHONE_STATE"/> <!--SDK permissions and <application        Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name"        Android:theme= "@style/apptheme" > <activity    Android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <activity android:theme=" @android: Style/theme.notitlebar "Android:name=" Com.sina.weibo.sdk.component.WeiboSdkBrowser "android:configch Anges= "Keyboardhidden|orientation" android:exported= "false" Android:windowsoftinputmode= "AdjustResiz E "> </activity> <activity android:name=". Authorizeactivity "android:label=" @string/title_activity_authorize "> </activity> <se Rvice android:name= "Com.sina.weibo.sdk.net.DownloadService" android:exported= "false" ></service> </ Application></manifest>

Sina Weibo SSO login mode and OAUTH2.0 certification and access to my Weibo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.