Android development my Sina Weibo client-use webview to replace the original built-in browser in the oauth authentication process

Source: Internet
Author: User
Tags oauth

In the previous article, the oauth authentication process obtains the oauth_verifier code by calling the browser in the Android system for user authorization authentication. For details, see: android development my Sina Weibo client-user authorization page function (3.2 ).

The original implementation is as follows:

1. First in androidmanifest. add the following configuration to authorizeactivity in XML: <data Android: Scheme = "MyApp" Android: host = "authorizeactivity"/>. In this way, the address MyApp is used in the browser: // authorizeactivity starts the activity authorizeactivity.

2. When the user authorization page is displayed in the browser of the Android system, use "MyApp: // authorizeactivity" as the URL parameter callbackurl = MyApp: // authorizeactivity, in this way, after entering the account and password, the user will request MyApp: // authorizeactivity? Oauth_verifier = 123456. At this time, authorizeactivity is started.

3. When authorizeactivity is started, use URI uri = intent. getdata (); In the onnewintent method to get the oauth_verifier value 123456.

This implementation has the following drawbacks:

That is, when user authentication is performed using a third-party browser such as UC for user authentication, when the user enters the account password and clicks the authorization button, the activity will not jump to the authorizeactivity, only the browser that comes with Android is correct. In fact, this is a serious problem. Most users will use third-party browsers such as UC, which leads to abnormal authentication.

I recently found a good idea when I tried oauth authentication on the iPhone, that is, do not use a browser with the system and embed a webview in your own program to complete user authorization authentication in this webview control without using additional browsers. Today, I moved the idea of implementation under the iPhone to Android and made the following attempts.

The current implementation is as follows:

1. The above three points can be removed first. Delete the deletion.

2. Create a viewactivity named webviewactivity. In this viewactivity, there is only one webview control.

The layout file is as follows:

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"     android:layout_height="wrap_content"    android:orientation="vertical">  <WebView   android:layout_height="wrap_content"            android:layout_width="wrap_content"  android:id="@+id/web">  </WebView>  </ScrollView>

3. After obtaining (request token and request Secret), modify the oauth process and start webviewactivity. The webview control of the webviewactivity displays the user-authenticated webpage. The code is implemented as follows:

// URL is similar to: http://api.t.sina.com.cn/oauth/authenticate? Oauth_token = 71c6df7fd0b4e1e5c491faa90b654fdf & from = xweibostring url = getauthenticationurl (); intent = new intent (mainactivity. this, webviewactivity. class); bundle B = new bundle (); B. putstring ("url", URL); intent. putextras (B); startactivity (intent );

4. In webviewactivity, obtain the previously passed URL in the oncreate method to display the authentication webpage. The Code is as follows:

Super. oncreate (savedinstancestate); setcontentview (R. layout. webview); webview WV = (webview) findviewbyid (R. id. web); intent I = This. getintent (); If (! I. Equals (null) {bundle B = I. getextras (); If (B! = NULL) {If (B. containskey ("url") {string url = B. getstring ("url"); // This line is important. Otherwise, the page's authentication button will be invalid WV. getsettings (). setjavascriptenabled (true); WV. getsettings (). setsuppzoom zoom (true); // WV. getsettings (). setdefaultzoom (websettings. zoomdensity. FAR); WV. getsettings (). setbuiltinzoomcontrols (true); WV. loadurl (URL );}}}

5. The callbackurl parameter is not provided in the above URL parameters. At this time, when the user enters the account and password and clicks authorization, the PIN code (oauth_verifier value) page is displayed instead of being redirected, the page is as follows:


6. The authorization code has been displayed in webview in the previous step. The next step is to obtain the authorization code 176048. Since this is a Web page displayed in webview, then we can retrieve the HTML code displayed in the current webview and then extract the authorization code. You can call JavaScript to obtain HTML code. You can easily explain the code and add the following code in the oncreate method:

wv.addJavascriptInterface(new JavaScriptInterface(), "Methods"); WebViewClient wvc=new WebViewClient()        {            @Override            public void onPageFinished(WebView view,String url)            {                view.loadUrl("javascript:window.Methods.getHTML('

Add javascriptinterface

Class javascriptinterface {public void gethtml (string html) {string pin = getpin (HTML); // The obtained PIN code is the oauth_verifier value, used to further obtain access token and access secret using log. E ("pin", pin );}}

7. In this way, we can get the HTML code of the current webview. The next step is to extract the authorization code in HTML. the HTML code is as follows:

<Head> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "> <meta name =" viewport "content =" width = device-width "> <title> application authorization-Sina Weibo </title> <link href =" http://timg.sjs.sinajs.cn/t35/style/css/open/open_third.css "rel =" stylesheet "type =" text/CSS "> 

The Java method code is as follows:

public String getPin(String html)    {        String ret="";        String regEx="[0-9]{6}";        Pattern p=Pattern.compile(regEx);        Matcher m=p.matcher(html);        boolean result=m.find();        if(result)        {            ret= m.group(0);        }        return ret;    }

In this way, all implementations are completed. Although this is a little troublesome, it completely solves the existing problems.

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.