Sina Weibo Oauth2.0 authorized authentication and use of SDK and API (Android)

Source: Internet
Author: User

----------------------------------------------------------------------------------------------

[ Copyright: The author of this article is original, reproduced please indicate the source ]
Article Source: http://blog.csdn.net/sdksdk0/article/details/51939853
Juppé id:sdksdk0 Email: [Email protected]

--------------------------------------------------------------------------------------------


This article mainly introduces the API access of Sina Weibo client, realizes the third-party authorization login function, and calls the API. Requires hands-on practical action, learning basic authorization mechanisms and calls to commonly used APIs. Here is mainly a Android application, at the end of the text to provide source download.


First, the use of Weibo developer platform

Sina Micro-blog This is mainly about the developer platform that uses Sina Weibo. If you want to do a microblog landing or a series of other operations, we must first login to their website to register for use, first of all to register as a developer. http://open.weibo.com/. Weibo open platform for mobile applications to provide a convenient mode of cooperation, to meet the diversified mobile end users anytime, anywhere fast login, sharing information needs, to help achieve mobile apps, health equipment, smart home, car and other types of terminal social access.

1. After registering for login, go to "micro connection", "mobile app", create an app. Then you can set it up for yourself.



2. After creation, go to "My apps", "Apply information," and "basic information" to set up. This is where you can set up your app's basic information. After filling in your package name, you need to download the SDK file.



3. Download the SDK file for Android here. Https://github.com/sinaweibosdk/weibo_android_sdk

Find a app_signatures.apk here, then install to your phone, click to run, put your package name into the after, will generate a serial number, and then copy the serial number to the earlier mentioned in the developer platform---"Android Signature package name information"-  >android signature. Finally, the app key and app Secret will be generated. These two things we'll use later.


4, OAuth2.0 authorization settings. Click on "Advanced Info", authorization settings, set authorization callback page and cancel authorization callback page. What I'm setting here is http://www.tianfang1314.cn/. You can set this place yourself.


Finally: The basic setup work is done here. The last we need to get from here is the PP key and app Secret, and the URL of the callback page



Second, Oauth2.0 authorized authentication mechanism

n Sina Weibo Android SDK provides developers with Oauth2.0 Authorization and integrated SSO login function, Enable third-party apps to perform authorization logins without needing to understand complex authentication mechanisms and provide Weibo sharing, and third-party apps can be shared directly via Weibo clients. There are three ways to authorize the Sina Weibo Android SDK.




Oauth2.0 protocol:

Allows users to provide a token instead of a user name and password to access their data stored in a particular service provider. each token authorizes a specific website (for example, a video editing site) to access a specific resource (for example, a video in only one album) within a specific period of time (for example, within the next 2 hours). this way, OAuth allow users to authorize third-party websites to access information that they store on other service providers without having to share their access licenses or all of the content of their data.



Third, using the Weibo SDK in Android Studio

First import the Sina Weibo SDK file: Do not directly copy the library into the project folder, so that there may be a variety of other unknown errors, it is recommended that the Import module method of importing the library file. Then select the Weibo library in the File->project Structure->dependencies->3model dependency. The library was imported successfully at this time.

Layout file I do not write out here, need to go to my text at the end of the address provided for download. Here are the main ways to use. First we need to create a new utils package to hold some of the authorized information. These files can be found directly in the official demo of the downloaded SDK. The main contents are:


Accesstokenkeeper.java

public class Accesstokenkeeper {private static final string PREFERENCES = "Sina";p rivate static final String key_uid = "UI D ";p rivate static final String key_access_token =" Access_token ";p rivate static final String key_expires_in =" Expires_in " ;p ublic static void Writeaccesstoken (context context, Oauth2accesstoken token) {if (context = = NULL | | token = = NULL) {RET Urn;} Sharedpreferences preferences = context.getsharedpreferences (preferences, context. Mode_append); Editor editor = Preferences.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,context.mode_append); 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,context.mode_append); Editor editor = Pref.edit (); Editor.clear (); Editor.commit ();}}


Constants.java.

Notice here that the Appkey and Appsecret we got in front of the developer platform are going to be here to use. Here to replace your. There is the callback page, also need to set up, remember: The URL of the callback page should not be wrong, and your original configuration is the same, the wrong letter is not OK!

public class Constants {public static final string app_key = "Replace with your Appkey";p ublic static final string app_secret = "Replace with your APP _secret ";/** * Callback page for the current DEMO app, a third-party app can use its own callback page. * We recommend using the default callback page: https://api.weibo.com/oauth2/default.html */public static final String Redirect_url = "/http/ www.tianfang1314.cn/";/** * Weibosdkdemo apply the corresponding permissions, third-party developers generally do not need so much, can be directly set to empty. For details, see the corresponding comments in the Demo. */public static final String SCOPE = "Email,direct_messages_read,direct_messages_write," + "friendships_groups_read, Friendships_groups_write,statuses_to_me_read, "+" follow_app_official_microblog, "+" Invitation_write ";p ublic Static final String user_show = "Https://api.weibo.com/2/users/show.json?uid={0}&access_token={1}";p ublic static Final String public_timeline = "https://api.weibo.com/2/statuses/public_timeline.json?access_token={0}";p ublic Static final String Friends_timeline = "https://api.weibo.com/2/statuses/friends_timeline.json?access_token={0}"; public static final String home_timeline = "https://api.weibo.com/2/statuses/home_timeline.json?count=20&access_token={0} ";p ublic static final String bilateral_timeline =" https ://api.weibo.com/2/statuses/bilateral_timeline.json?count=20&access_token={0} ";p ublic static final String repost = "Https://api.weibo.com/2/statuses/repost.json";p ublic static final String updata = "https://api.weibo.com/2/ Statuses/update.json ";p ublic static final String comment_show =" Https://api.weibo.com/2/comments/show.json?access_ token={0} ";p ublic static final String comment_create =" Https://api.weibo.com/2/comments/create.json ";p ublic static Final string Friendships_destroy = "Https://api.weibo.com/2/friendships/destroy.json";p ublic static final string Friendships_create = "Https://api.weibo.com/2/friendships/create.json";p ublic static final String followers = "https:/ /api.weibo.com/2/friendships/followers.json ";p ublic static final String user_timeline =" https://api.weibo.com/2/ Statuses/user_timeline.json ";p ublic static final String delete =" Https://api.weibo. Com/2/statuses/destroy.json ";p ublic static final String friendship_friends =" https://api.weibo.com/2/friendships/ Friends.json ";p ublic static final String replay =" Https://api.weibo.com/2/comments/reply.json ";p ublic static final String bilateral_timeline2 = "Https://api.weibo.com/2/statuses/bilateral_timeline.json";p ublic static final String mentions = "Https://api.weibo.com/2/statuses/mentions.json";p ublic static final String weekly = "https://api.weibo.com /2/trends/weekly.json ";p ublic static final String daily =" Https://api.weibo.com/2/trends/daily.json ";p ublic static Final string hourly = "Https://api.weibo.com/2/trends/hourly.json";p ublic static final string users = "Https://api.weibo . Com/2/search/suggestions/users.json ";p ublic static final String upload =" https://upload.api.weibo.com/2/statuses/ Upload.json ";p ublic static final String comment_mentions =" Https://api.weibo.com/2/comments/mentions.json ";}

Httputils.java


public class Httputils {/** * returns an input stream via URL address * * @param URL * address * @return input stream */public static InputStream Geti Nputstream (String url) {URL Home_url = null;inputstream input = null; HttpURLConnection conn = null;try {home_url = new URL (URL); conn = (httpurlconnection) home_url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (); Conn.connect (); input = Conn.getinputstream ();} catch (IOException e) {e.printstacktrace ();} return input;} /** * Return String * * @param URL * @return */public static string getstringbystream (string url) {StringBuilder SB = null; BufferedReader br = Null;inputstream input = getinputstream (URL); if (input! = null) {br = new BufferedReader (New Inputstre Amreader (input)); String line = NULL;SB = new StringBuilder (), try {(line = Br.readline ())! = null) {sb.append (line);}} catch (Ioexcep tion e) {e.printstacktrace ();}} ELSE{SB = new StringBuilder ("");} return sb.tostring ();}}

Next we need to write the Java code of the interface.

Login to Weibo

Loginactivity.java

public class Loginactivity extends Activity {AuthInfo mauthinfo; Ssohandler ssohandler;oauth2accesstoken accesstoken; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_login); Initdatas ();} /** * Data initialization */private void Initdatas () {//Context Mauthinfo = new AuthInfo (Loginactivity.this, Constants.app_key, constants.re Direct_url,constants.scope); Ssohandler = new Ssohandler (loginactivity.this, Mauthinfo); Ssohandler.authorize (new Weiboauthlistener () {//authentication failed @overridepublic void Onweiboexception (Weiboexception arg0) {Toast.maketext ( Loginactivity.this, "Authentication failed" +arg0, Toast.length_short). Show (); Certified successful @overridepublic void OnComplete (Bundle arg0) {Accesstoken = Oauth2accesstoken.parseaccesstoken (arg0);// Verify that our token is valid if (Accesstoken.issessionvalid ()) {Accesstokenkeeper.writeaccesstoken (loginactivity.this, AccessToken) ; Toast.maketext (Loginactivity.this, "Certified successful", Toast.length_short). Show ();}} De-certified @overridepublic void OnCancel () {//TODO auto-generated Method Stubtoast.maketext (Loginactivity.this, "Cancel Authentication", Toast.length_short). Show ();}});}} 

Send Weibo:

public class Sendweibo extends Activity {//token oauth2accesstoken Accesstoken; Statusesapi statusesapi;private EditText et_weibo;private Button Btn_sendweibo; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_sendweibo); Initdatas (); Initviews ();} private void Initviews () {Et_weibo = (EditText) Findviewbyid (R.id.et_weibo); Btn_sendweibo = (Button) Findviewbyid ( R.id.btn_sendweibo); Btn_sendweibo.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) { String Weibo = Et_weibo.gettext (). toString (); if (! Textutils.isempty (Weibo)) {statusesapi.update (Weibo, NULL, NULL, new Requestlistener () {@Overridepublic void Onweiboexception (weiboexception arg0) {toast.maketext (Sendweibo.this, "Send Failed", Toast.length_short). Show (); @Overridepublic void OnComplete (String arg0) {toast.maketext (Sendweibo.this, "Send Success", Toast.length_short). Show ();});}}); }private void Initdatas () {Accesstoken = Accesstokenkeeper.readaccesstokeN (sendweibo.this); statusesapi = new Statusesapi (Sendweibo.this, Constants.app_key, Accesstoken);}} 


Main interface Call:

public class Mainactivity extends Activity {private static final String TAG = MainActivity.class.getSimpleName (); private static final demoinfo[] Demos = {New Demoinfo ("Login micro-blog", "First", Loginactivity.class), new Demo    Info ("Send micro-blog", "Second", Sendweibo.class)};        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        TextView Text = (TextView) Findviewbyid (r.id.text_info);        Text.settextcolor (color.red);        Text.settext ("Sina Weibo example");        ListView Mlistview = (ListView) Findviewbyid (R.id.listview);        Add ListItem, set event response Mlistview.setadapter (New Demolistadapter ()); Mlistview.setonitemclicklistener (New Adapterview.onitemclicklistener () {public void Onitemclick (adapterview&lt ;?            > arg0, View v, int index, long arg3) {Onlistitemclick (index);    }        }); } public void Onlistitemclick (int index) {Intent Intent = null;        Intent = new Intent (mainactivity.this, demos[index].democlass);        LOG.D (TAG, "ItemClick ()");    This.startactivity (Intent); }/** * Demo List Adapter * * */Private class Demolistadapter extends Baseadapter {public Demolista        Dapter () {super (); } @Override public View getView (int index, view Convertview, ViewGroup parent) {Convertview = Vi            Ew.inflate (mainactivity.this, r.layout.demo_info_item, NULL);            TextView title = (TextView) Convertview.findviewbyid (r.id.title);            TextView desc = (TextView) Convertview.findviewbyid (R.ID.DESC);            Title.settext (Demos[index].title);            Desc.settext (DEMOS[INDEX].DESC);            if (index >=) {title.settextcolor (color.yellow);        } return Convertview;      } @Override public int getcount () {      return demos.length;        } @Override public Object getItem (int index) {return demos[index];        } @Override public long getitemid (int id) {return id;        }}/** * Item information * */private static class Demoinfo {private final String title;        Private final String desc; Private final class<?        Extends android.app.activity> DemoClass;             Public Demoinfo (string title, String desc, class<? extends android.app.activity> DemoClass) {            This.title = title;            THIS.DESC = desc;        This.democlass = DemoClass; }    }}



Last and last. The permissions are configured in the manifest file when we need to.


<uses-permission 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 "/>    <uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<activity android:name= "com.zhilinghui.weibo.ui.LoginActivity" >        </activity>        <activity Android:name= "Com.zhilinghui.weibo.ui.SendWeibo" >        </activity>        <!--must be registered on Weibo and used to share micro-blog.        <activity            android:name= "Com.sina.weibo.sdk.component.WeiboSdkBrowser"            android:configchanges= " Keyboardhidden|orientation "            android:exported=" false "            android:windowsoftinputmode=" Adjustresize ">        </activity>

Here, we are all developed, you can directly use the micro-blog to login, but also to send the function of Weibo.


Summary: This case is, in general, very simple, and there are some details that need to be dealt with further. For all kinds of weird small bugs need time to debug, need a lot of patience. When registering the Sina Weibo developer platform, the application settings and package signature, page callback and so on need to deal with, really patience and careful is very important. Share!

If you have any questions, please contact: [email protected] (email)




SOURCE Download: http://download.csdn.net/detail/sdksdk0/9578861

Https://github.com/sdksdk0/SinaWeiboDemo

Sina Weibo Oauth2.0 authorized authentication and use of SDK and API (Android)

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.