Android Sina Weibo oauth2.0 certification and custom webview Certification

Source: Internet
Author: User
Tags oauth

First of all, I had to say that I had made a hole mistake, but I cannot blame myself completely, because everyone knows that the jar package provided by Sina Weibo oauth2.0 is more than 2 MB, no one seems to want to use it, so that I can study the use of 1.0. After a long time, I finally realized that it is available. Sina, the newest of the abnormal saying, wants to stop calling the 1.0 interface, I have to change it. Think about it as well. People upgrade it to make it easy to use. Well, don't complain, because Sina oauth2.0 is much more convenient and easier to use than 1.0. Here I will briefly explain:

First of all, I don't like the jar package method provided by Sina, So I integrated their source code into my application, which looks intuitive. in fact, it is very easy to copy the com.weibo.net package to your own project, and fix the bug. I will not talk about it here. The following describes how to use it:

Code snippet:

Weibo = Weibo. getinstance (); Weibo. setupconsumerconfig (consumer_key, consumer_secret); Weibo. setredirecturl (mredirecturl); // authenticate Weibo. authorize (mainactivity. this, new myweibodialoglistener ());
Class myweibodialoglistener implements weibodialoglistener {@ overridepublic void oncomplete (bundle values) {/*** save token and expires_in */string token = values. getstring ("access_token"); // obtain access_tokeneditor = preferences. edit (); Editor. putstring ("token", token); Editor. commit (); toast. maketext (mainactivity. this, Token, 1000 ). show (); // string expires_in = values. getstring ("expires_in"); // accesstoken = new accesstoken (token, consumer_secret); // accesstoken. setexpiresin (expires_in); intent = new intent (); intent. setclass (mainactivity. this, mainactivity. class); startactivity (intent) ;}@ overridepublic void onweiboexception (weiboexception e) {}@ overridepublic void onerror (dialogerror e) {}@ overridepublic void oncancel (){}}

In the above Code, we only need to save the token and expires_in values in the interface (so that we do not need to authenticate oauth again in the future), but we can only save the token, the value of expires_in is just a form. If it expires, the token will be invalid. At this time, you should re-Authenticate and obtain the new token value. (This is what we say here, I have not investigated it. I have time to study it and draw a conclusion. don't mind)

Send call:

If (token = NULL | token. equals ("") {toast. maketext (mainactivity. this, "oauth authentication first", 1000 ). show ();} else {utility. setauthorization (New oauth2accesstokenheader (); // This step cannot be saved. accesstoken = new accesstoken (token, consumer_secret); Weibo. getinstance (). setaccesstoken (accesstoken); Update (Weibo. getinstance (), Weibo. getappkey (), edittext. gettext (). tostring (), "", "");/***** obtain the corresponding interface data * // try {// getpublictimeline (Weibo. getinstance (); //} catch (malformedurlexception e) {// todo auto-generated Catch Block // E. printstacktrace (); //} catch (ioexception e) {// todo auto-generated Catch Block // E. printstacktrace ();//}}

Official source code:

    private void authorize(Activity activity, String[] permissions, int activityCode,            final WeiboDialogListener listener) {        Utility.setAuthorization(new Oauth2AccessTokenHeader());        boolean singleSignOnStarted = false;        mAuthDialogListener = listener;        // Prefer single sign-on, where available.        if (activityCode >= 0) {            singleSignOnStarted = startSingleSignOn(activity, APP_KEY, permissions, activityCode);        }        // Otherwise fall back to traditional dialog.        if (!singleSignOnStarted) {            startDialogAuth(activity, permissions);        }    }


Utility. setauthorization (New oauth2accesstokenheader ());

This statement should be executed before you create an accesstoken. Remember this, and I am not at a high level.

In this way, we have published a microblog.

At last, we also need to note that there is a deficiency in using their dialog authentication directly in our applications.


In fact, there is nothing, that is, it is inconvenient to use, and it will cover this view if you don't move it. Because the official website provides a dialog, we cannot use it.

Android: windowsoftinputmode = "adjustpan | statealwaysvisible"

But we can implement it in the Code. Add the following to oncreate in com.weibo.net. weibodialog. Java:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

In this way, we will not cover my iew. The effect is as follows:


You see, this will not affect you. By the way, I have processed dialog myself. You can also process it according to your own perspective.




The above is a brief introduction here, because the self-feeling is not flexible, let's look at several application views:



It looks friendly, so you need to create your own webview activity.

Next I will introduce how to implement it:

Create mywebviewactivity. Java

Package COM. JJ. sina; import android. app. activity; import android. content. intent; import android. content. sharedpreferences; import android. content. sharedpreferences. editor; import android. graphics. bitmap; import android.net. uri; import android.net. HTTP. sslerror; import android. OS. bundle; import android. util. log; import android. view. view; import android. webKit. sslerrorhandler; import android. webKit. webchromeclient; import android. webKit. webview; import android. webKit. webviewclient; import android. widget. linearlayout; import android. widget. toast; import com.weibo.net. accesstoken; import com.weibo.net. dialogerror; import com.weibo.net. utility; import com.weibo.net. weibo; import com.weibo.net. weibodialoglistener; import com.weibo.net. weiboexception;/***** custom webview (oauth authentication) ** @ author Zhangjia **/public class mywebviewactivity extends activity implements weibodialoglistener {private final string tag = "jjhappyforever "; private webview mwebview; private weibodialoglistener mlistener; private linearlayout; Public void initwebview () {linearlayout = (linearlayout) findviewbyid (R. id. ll_webview); mwebview = (webview) findviewbyid (R. id. mywebview); mwebview. setverticalscrollbarenabled (false); mwebview. sethorizontalscrollbarenabled (false); mwebview. getsettings (). setjavascriptenabled (true); mwebview. setwebviewclient (New weibowebviewclient (); mwebview. loadurl (myweibomanager. getoauthurl (this);} @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); mlistener = This; setcontentview (R. layout. webview); initwebview ();} /***** webviewclient ** @ author Zhangjia **/private class weibowebviewclient extends webviewclient {/***** address change will call */@ overridepublic Boolean shouldoverrideurlloading (webview view, string URL) {log. D (TAG, "Redirect URL:" + URL); If (URL. startswith (Weibo. getinstance (). getredirecturl () {handleredirecturl (view, URL); Return true;} // launch non-dialog URLs in a full browserstartactivity (new intent (intent. action_view, Uri. parse (URL); Return true;} @ overridepublic void onreceivederror (webview view, int errorcode, string description, string failingurl) {super. onreceivederror (view, errorcode, description, failingurl); mlistener. onerror (New dialogerror (description, errorcode, failingurl) ;}@ overridepublic void onpagestarted (webview view, string URL, bitmap favicon) {log. D (TAG, "onpagestarted URL:" + URL); // Google issue. shouldoverrideurlloading not executed/*** click "authorize". The URL is correct */If (URL. startswith (Weibo. getinstance (). getredirecturl () {handleredirecturl (view, URL); view. stoploading (); return;} super. onpagestarted (view, URL, favicon) ;}@ overridepublic void onpagefinished (webview view, string URL) {log. D (TAG, "onpagefinished URL:" + URL); super. onpagefinished (view, URL); linearlayout. setvisibility (view. gone);} public void onreceivedsslerror (webview view, sslerrorhandler handler, sslerror error) {handler. proceed () ;}} private void handleredirecturl (webview view, string URL) {bundle values = utility. parseurl (URL); string error = values. getstring ("error"); string error_code = values. getstring ("error_code"); // If (error = NULL & error_code = NULL) {mlistener. oncomplete (values); // rejection failed, etc.} else if (error. equals ("access_denied") {mlistener. oncancel ();} else {// mlistener exception. onweiboexception (New weiboexception (error, integer. parseint (error_code); }}@ overridepublic void oncomplete (bundle values) {/*** Save the access_token */string token = values here. getstring ("access_token"); sharedpreferences preferences = getsharedpreferences (mainactivity. file, 0); Editor editor = preferences. edit (); Editor. putstring ("token", token); Editor. commit (); accesstoken = new accesstoken (token, Weibo. getappsecret (); Weibo. getinstance (). setaccesstoken (accesstoken); setresult (result_ OK); finish () ;}@ overridepublic void onweiboexception (weiboexception e) {e. printstacktrace () ;}@ overridepublic void onerror (dialogerror e) {e. printstacktrace () ;}@ overridepublic void oncancel () {finish ();}}

Most of the above Code is the code in copy weibodialog. Java, just a slight change.

There are two most important parts: first, how to get the URL to be loaded, that is, the display of the authentication interface, and second, how to get the access_token value. With this value, we can call the API.

It's hard to understand.

(I won't cover up the first one, but the last one is)


The above is just a prototype. You can adjust the application according to your own project type. Does this look much better than calling the android Sina jar package directly,

In addition, the implementation is also flexible, and Sina oauth2.0 is not bad.


The source code is uploaded to the Internet. If you have any questions, please leave a message.

Thanks for you! ! !


Source code download






Related Article

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.