天天看點

WebView執行個體開發之人人網Oauth2認證

今天做了一個webview網絡操作的執行個體,這裡與大家分享。相信開發過新浪、騰訊、豆瓣以及人人等微網誌的開發者都知道OAuth這個認證架構。這些開放平台上也有自己開發好了的SDK,隻需要下載下傳過來即可使用。今天主要是結合webview來實作人人網的認證授權。 

   OAuth 2.0驗證授權流程,支援網站、站内應用、手機用戶端、桌面用戶端等。 具體可以參考:

   人人的開放平台的認證流程:http://wiki.dev.renren.com/wiki/Authentication

   OAuth2.0的協定标準:http://oauth.net/2/

在android的浏覽器應用中,經常會使用到webview。這裡webview的概念網絡上一大堆,這裡直接複制網絡上的描述:

WebView(網絡視圖)能加載顯示網頁,可以将其視為一個浏覽器。它使用了WebKit渲染引擎加載顯示網頁,實作WebView有以下兩種不同的方法:

第一種方法的步驟:

1.在要Activity中執行個體化WebView元件:WebView webView = new WebView(this);

2.調用WebView的loadUrl()方法,設定WevView要顯示的網頁:

3.調用Activity的setContentView( )方法來顯示網頁視圖

4.用WebView點連結看了很多頁以後為了讓WebView支援回退功能,需要覆寫覆寫Activity類的onKeyDown()方法,如果不做任何處理,點選系統回退剪鍵,整個浏覽器會調用finish()而結束自身,而不是回退到上一頁面

5.需要在AndroidManifest.xml檔案中添權重限,否則會出現Web page not available錯誤。

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

嘿嘿以上的描述說的挺清楚的了。

以下是webview開發的執行個體,擷取人人的授權token的核心代碼

package com.xzw.token; 

import java.io.BufferedReader; 

import java.io.IOException; 

import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 

import org.apache.http.HttpResponse; 

import org.apache.http.client.ClientProtocolException; 

import org.apache.http.client.HttpClient; 

import org.apache.http.client.methods.HttpGet; 

import org.apache.http.impl.client.DefaultHttpClient; 

import org.json.JSONException; 

import org.json.JSONObject; 

import android.app.Activity; 

import android.app.AlertDialog; 

import android.app.ProgressDialog; 

import android.content.DialogInterface; 

import android.graphics.Bitmap; 

import android.os.Bundle; 

import android.util.Log; 

import android.view.Window; 

import android.webkit.WebSettings; 

import android.webkit.WebView; 

import android.webkit.WebViewClient; 

import android.widget.Toast; 

public class OAuthActivity extends Activity { 

    private static final String TAG = "OAuthActivity"; 

    private static final String CLIENT_ID = "e2e5e39bf9ff4b5a8245735a94d50e86"; // 應用的APPkey 

    private static final String CLIENT_SECRET = "b6ba1f9fa8ff47889abe2e2d5928d6fd"; //應用的appke secret 

    private static final String REDIRECT_URL = "http://192.168.51.141"; // 重定向位址 

    private static final String AUTHORIZE_URL = "https://graph.renren.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code"; // Oauth2認證位址 

    private static final String ACCESS_TOKEN_URL = "https://graph.renren.com/oauth/token?grant_type=authorization_code&client_id=%s&redirect_uri=%s&client_secret=%s&code=%s"; 

    private WebView mLoginWebView; 

    private ProgressDialog progressDialog; 

    private AlertDialog alertDialog; 

    @Override 

    public void onCreate(Bundle savedInstanceState) { 

        super.onCreate(savedInstanceState); 

        requestWindowFeature(Window.FEATURE_NO_TITLE); 

        setContentView(R.layout.activity_main); 

        initWebView();// 初始化webview 

    } 

    /** 

     * 初始化webview 

     */ 

    private void initWebView() { 

        mLoginWebView = (WebView) findViewById(R.id.loginView); 

        WebSettings settings = mLoginWebView.getSettings(); 

        settings.setJavaScriptEnabled(true);//設定支援javascript 

        settings.setSupportZoom(true);  // 

        settings.setBuiltInZoomControls(true); //設定支援縮放 

        String url = String.format(AUTHORIZE_URL, new Object[] { CLIENT_ID, 

                REDIRECT_URL }); 

        // 加載網頁 

        mLoginWebView.loadUrl(url);   

        // 網頁加載進度條 

        progressDialog = ProgressDialog.show(this, null, "正在加載,請稍後..."); 

        alertDialog = new AlertDialog.Builder(this).create(); //建立AlertDialog 

        mLoginWebView.setWebViewClient(new MyWebViewClient()); 

    class MyWebViewClient extends WebViewClient { 

        /** 

         * 攔截URL位址,進行業務操作 

         */ 

        @Override 

        public boolean shouldOverrideUrlLoading(WebView view, String url) { 

            Log.i(TAG, "-shouldOverrideUrlLoading--startwith-" + url); 

            String callback_url = REDIRECT_URL + "/?"; 

            if (url.startsWith(callback_url)) { //比對callback_url 

                Log.i(TAG, "-shouldOverrideUrlLoading--" + url); 

                String code = url.replace(callback_url + "code=", ""); 

                System.out.println("code=" + code); 

                String urlString = String.format(ACCESS_TOKEN_URL, 

                        new Object[] { CLIENT_ID, REDIRECT_URL, CLIENT_SECRET, 

                                code }); 

                parseUrl(urlString); 

                return false; 

            } else { 

                view.loadUrl(url); 

                return true; 

            } 

        } 

        public void onPageStarted(WebView view, String url, Bitmap favicon) { 

            Log.i(TAG, "-onPageFinished-" + url); 

            if (!progressDialog.isShowing()) { //網頁開始加載時,顯示進度條。 

                progressDialog.show(); 

        public void onPageFinished(WebView view, String url) { 

            if (progressDialog.isShowing()) { // 加載完畢後,進度條不顯示 

                progressDialog.dismiss(); 

        public void onReceivedError(WebView view, int errorCode, 

                String description, String failingUrl) { 

            Log.i(TAG, "-onReceivedError-" + failingUrl); 

            Toast.makeText(OAuthActivity.this, "網頁加載出錯", Toast.LENGTH_LONG) 

                    .show(); 

            alertDialog.setTitle("Error"); 

            alertDialog.setMessage(description); 

            alertDialog.setButton("ok", new DialogInterface.OnClickListener() { 

                @Override 

                public void onClick(DialogInterface dialog, int which) { 

                } 

            }); 

            alertDialog.show(); 

     * URL解析 

     * @param url 

    private void parseUrl(String url){  

        HttpClient client = new DefaultHttpClient(); 

        HttpGet get = new HttpGet(url); 

        try { 

            HttpResponse response = client.execute(get); 

            HttpEntity entity = response.getEntity();  

            BufferedReader buffReader = new BufferedReader(new InputStreamReader( 

                    entity.getContent())); 

            StringBuffer strBuff = new StringBuffer(); 

            String result = null; 

            while ((result = buffReader.readLine()) != null) { 

                strBuff.append(result); 

            System.out.println(strBuff.toString()); 

            parseJson(strBuff.toString()); 

        } catch (ClientProtocolException e) { 

            // TODO Auto-generated catch block 

            e.printStackTrace(); 

        } catch (IOException e) { 

     * json解析 

     * @param strJson 

    private void parseJson(String strJson){ 

            JSONObject json = new JSONObject(strJson); 

            int expires_in = json.getInt("expires_in"); 

            String refresh_token = json.getString("refresh_token"); 

            String access_token = json.getString("access_token"); 

            System.out.println("過期時間="+expires_in+" \naccess_token="+access_token); 

        } catch (JSONException e) { 

看下效果圖:

<a href="http://blog.51cto.com/attachment/201210/193509333.png" target="_blank"></a>

 歡迎大家一起學習交流。源碼已上傳

本文轉自xuzw13 51CTO部落格,原文連結:http://blog.51cto.com/xuzhiwei/1031871,如需轉載請自行聯系原作者

繼續閱讀