Android authorized to log on to Sina Weibo for user personal information

Source: Internet
Author: User
Tags oauth

Reprint Please specify source:http://blog.csdn.net/u010214991/article/details/49149793

I remember the first time I wrote an article titled " Android uses the official API to share content to QQ and (non-third party integration)", which describes how to use the official SDK to realize the sharing function. So today we talk about how to use Sina Weibo authorized login to obtain user information, we all know, now many software in addition to local registration login, but also added third-party login function, the most common is directly authorized QQ and other software to log in the application without self-registration, The principle is to obtain third-party user information through open protocol OAuth to achieve this goal. This article is based on OAuth authentication to obtain Sina Weibo user information.


First, the preparatory work

We all know that whether it is to share to Sina Weibo, or access to Sina Weibo user information, is inseparable from the same thing, that is, Sina Weibo appid,appid by binding our application's package name and signature to identify, it can be said that it is our official interface with Sina Weibo to interact with an important token , this is the same as QQ, interface and other access principles are basically the same. So here's the question, how did AppID get it? The answer is you have to register an account with the Sina Weibo open platform http://open.weibo.com/ , fill in and create your app. As shown in the following:

Clicking Create app will appear as shown in the page where you have to fill in your Android package name and Android signature, the package name is the string in your application Androidmanifest.xml file, such as you create a new name called " Test "project, then your package name should be com.example.test. As for the Android signature, you can download the signature tool on the open platform apk mount to the phone, then open the APK to fill in the package name to get the signature, or you can directly click on the developer tool Eclispe window->preferences->android- >build view, as shown, for other necessary filling information, you can improve yourself:

After filling out all the information, we click Submit Review, and note that only apps approved by the app will be able to invoke the APIs they provide.


Second, the project preparation

Create a new project with the package name that matches the name of the package you filled out. After the completion of the new download Sina Weibo sdk, download the completion of the decompression, the Libs directory files are all copied to your project Libs directory, the Weibosdkcore_3.1.2.jar package is also copied to the Libs directory, Find the Accesstokenkeeper.java, Usersapi.java, absopenapi.java files and copy them to your package, I'll post my project catalog, and I'll put the entire sample source on the back.

Note that the above common in the Sinauserinfo.java is built by me, just for the convenience of saving and fetching user information. Also, don't forget to add permissions in Androidmanifest.xml:

<uses-permission android:name= "Android.permission.INTERNET"/>


Third, write code

After several twists and turns, the following directly into the topic, paste code

1, Sinauserinfo.java (previously said, this class is very simple, just easy access to user information only)

public class Sinauserinfo {private string uid;//user Idprivate string name;//user nickname private string avatarhd;//user avatar Urlpublic Sinauserinfo () {super ();//TODO auto-generated constructor stub}public String Getuid () {return UID;} public void SetUid (String uid) {this.uid = uid;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String GETAVATARHD () {return AVATARHD;} public void Setavatarhd (String avatarhd) {THIS.AVATARHD = AVATARHD;}}

2.mainactivity.java (This is the core, the first step to explain, followed by directly post the complete code)

In this Java file, the specific process of authorizing login and obtaining information is such that the IWEIBOSHAREAPI is instantiated first through the AppID that we previously audited:

Weiboshareapi = Weibosharesdk.createweiboapi (context, swb_app_id);

Then get the OAuth protocol information and set the authorization callback interface:

AuthInfo = new AuthInfo (context, swb_app_id, Swb_redirect_url, swb_scope); ssohandler = new Ssohandler (mainactivity.this , authInfo); Ssohandler.authorize (new Authlistener ());
In the authorization callback interface, we parse the access token Accesstoken by using the parameter values in the OnComplete method, and save the Accesstoken by Accesstokenkeeper this class, so that we can complete the authorization, Then we open a thread, instantiate Usersapi and call the show () method, which has two parameters, because we are using accesstoken.getuid () that is the user ID to obtain the user information, So the parameter type here is a long instead of a string, and if you don't turn into long, he actually accesses the user's information through the user name, then it appears " com.weibo.sdk.android.WeiboException: {"error": "User does not exists!", "Error_code": 20003, "request": "/2/users/ Show.json "}", which is a phenomenon that the user does not exist.

@Overridepublic void OnComplete (Bundle values) {//TODO auto-generated method Stub accesstoken = Oauth2accesstoken.parsea Ccesstoken (values); Parse tokenstring phonenum = Accesstoken.getphonenum () from the bundle and get the phone number information entered by the user from here if (accesstoken.issessionval  ID ()) {Accesstokenkeeper.writeaccesstoken (mainactivity.this, Accesstoken);//Save Tokentoast.maketext (context,                      "Authorized Success", Toast.length_short). Show (); New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubusersapi Usersapi = new Usersapi ( Context, swb_app_id, Accesstoken), Usersapi.show (Long.valueof (Accesstoken.getuid ()), New Sinarequestlistener ());            }}). Start (); }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 you register the package name and sign on the platform Name does not match the package name and signature of the app you are currently testing. String code = values.getstring ("code"); String message = "Authorization Failed"; Textutils.isempty (code)) {message = message + "\nobtained The Code:" + code;} Toast.makeText (context, message, Toast.length_long). Show (); }         }
The second parameter in the Show method above is the Sina Weibo request listener callback interface, we can get the JSON data returned in the parameter Respon in the OnComplete method of this interface,
By parsing the JSON data we can get the Sina Weibo user information we want, and the entire process is over, and here is some code for the request interface.


public class Sinarequestlistener implements requestlistener{//Sina Weibo request interface               @Overridepublic void OnComplete (String Response) {//TODO auto-generated method stubtry {jsonobject jsonobject = new Jsonobject (response);  String idstr = jsonobject.getstring ("Idstr");//Unique identifier (UID)                string name = Jsonobject.getstring ("name");//Name                String AVATARHD = jsonobject.getstring ("AVATAR_HD");//Avatar  

To authorize a callback to work, don't forget to add the following code to the activity:

@Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub Super.onactivityresult (Requestcode, ResultCode, data), if (ssohandler! = null) {Ssohandler.authorizecallback ( Requestcode, ResultCode, data);}}


OK, here's the full code directly:

Import Org.json.jsonexception;import Org.json.jsonobject;import Android.app.activity;import Android.content.context;import Android.content.intent;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.text.textutils;import Android.util.log;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;import Android.widget.toast;import Com.gdruichao.bbt.common.sinauserinfo;import Com.sina.weibo.sdk.api.share.iweiboshareapi;import Com.sina.weibo.sdk.api.share.weibosharesdk;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;public Class Mainactivity extends Activity implements Onclicklistener{private Context context;private Iweiboshareapi Weiboshareapi; Private finAl static String swb_app_id = "3802299039";p rivate button login;private AuthInfo authinfo;private ssohandler ssohandler;p Rivate oauth2accesstoken accesstoken;private TextView userinfo_tv;private sinauserinfo userinfo;public static final String swb_redirect_url = "https://api.weibo.com/oauth2/default.html";//Sina Weibo callback page public static final String Swb_scope = "Email,direct_messages_read,direct_messages_write," + "friendships_groups_read,friendships_groups_write,statuses _to_me_read, "+" follow_app_official_microblog, "+" invitation_write "; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); context = this; Weiboshareapi = Weibosharesdk.createweiboapi (context, swb_app_id); userinfo_tv = (TextView) Findviewbyid ( R.ID.USERINFO_TV); login = (Button) Findviewbyid (R.id.login); Login.setonclicklistener (this);} @Overridepublic void OnClick (View v) {//TODO auto-generated Method stubauthinfo = new AuthInfo (context, swb_app_id, SWb_redirect_url, swb_scope); ssohandler = new Ssohandler (mainactivity.this, AuthInfo); Ssohandler.authorize (new Authlistener ());} public class Authlistener implements weiboauthlistener{@Overridepublic void OnCancel () {//TODO auto-generated method Stu Btoast.maketext (context, "authorization cancellation", Toast.length_long). Show (); @Overridepublic void OnComplete (Bundle values) {//TODO auto-generated method Stub accesstoken = Oauth2accesstoken.parsea Ccesstoken (values); Parse tokenstring phonenum = Accesstoken.getphonenum () from the bundle and get the phone number information entered by the user from here if (accesstoken.issessionval  ID ()) {Accesstokenkeeper.writeaccesstoken (mainactivity.this, Accesstoken);//Save Tokentoast.maketext (context,                                "Authorized Success", Toast.length_short). Show (); New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubusersapi Usersapi = new Usersapi ( Context, swb_app_id, Accesstoken), Usersapi.show (Long.valueof (Accesstoken.getuid ()), New Sinarequestlistener ()); }}). sTart (); }}else{///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 you register the package name and signature on the platform with the package name and signing of the app you are currently testing When the name does not match. String code = values.getstring ("code"); String message = "Authorization Failed"; Textutils.isempty (code)) {message = message + "\nobtained The Code:" + code;} Toast.maketext (context, message, Toast.length_long). Show (); } @Override public void Onweiboexception (Weiboexception e) {//TODO auto-generated Method Stubtoast.maketext (Context, " Auth exception: "+ E.getmessage (), Toast.length_long). Show ();}} Public Handler Handler = new Handler () {public void Handlemessage (Message msg) {if (msg.what = = 1) {userinfo_tv.settext ("User I D: "+userinfo.getuid () +" \ n "+" User name: "+userinfo.getname () +" \ n "+" User picture URL: "+USERINFO.GETAVATARHD ());};}; public class Sinarequestlistener implements requestlistener{//Sina Weibo request interface @override public void OnComplete (String response {//TODO auto-generated method stubtry {jsonobject jsonobject = new Jsonobject (response); String idstr = jsonobject.getstring ("Idstr");//Unique identifier (UID) string name = Jsonobject.getstring ("name");//name String AVATARHD = jsonobject.getstring ("AVATAR_HD");//Avatar UserInfo = new Sinauserinfo (); Userinfo.setuid (IDSTR); Userinfo.setname (name); USERINFO.SETAVATARHD (AVATARHD); Message message = Message.obtain (); Message.what = 1; Handler.sendmessage (message); } catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} @Overridepublic void Onweiboexception (Weiboexception e) {//TODO auto-generated Method Stubtoast.maketext (Context, " Auth exception: "+ E.getmessage (), Toast.length_long). Show (); LOG.I ("MyLog", "Auth exception:" + E.getmessage ());}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub Super.onactivityresult (Requestcode, ResultCode, data), if (ssohandler! = null) {Ssohandler.authorizecallback ( Requestcode, ResultCode, data);}}}



Iv. Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:id=" @+id/linearlayout1 "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    android:orientation= "vertical"    tools:context= ". Mainactivity ">    <button        android:id=" @+id/login "        android:layout_width=" Match_parent        " android:layout_height= "Wrap_content"        android:text= "Sina Weibo login get user information"/>    <textview        android:id= " @+id/userinfo_tv "        android:layout_width=" match_parent "        android:layout_height=" Match_parent        " Android:textsize= "20DP"        android:text= ""/></linearlayout>

Wu, Androidmanifest.xml

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" COM.GDRUICHAO.BBT "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android.permis Sion. INTERNET "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launcher "an Droid:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= "Co                M.gdruichao.bbt.mainactivity "android:label=" @string/app_name "> <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category android:name= "android.intent.c Ategory. LAUNCHER "/> </intent-filter> </activity> <!--Sina Weibo website authorized login related configuration--&lt ; Activity AndroId:name= "Com.sina.weibo.sdk.component.WeiboSdkBrowser" android:configchanges= "Keyboardhidden|orientation"            Android:exported= "false" android:windowsoftinputmode= "Adjustresize" > </activity> </application></manifest>

Actually added a network access rights and Sina Weibo website authorized login configuration, to prevent users do not have Sina Weibo client situation, if you already have Sina Weibo client, you can not add this page authorization this configuration, but for the sake of security you still add bar haha.


Finally attach the source code download, Android Authorized third-party login to get Sina Weibo user information, be careful to change your AppID and package name when you run the test. Well, this is the end of this article, welcome to have questions or suggestions of children's shoes warmly vindicate, we see next time!

Android authorized to log on to Sina Weibo for user personal information

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.