今天做了一个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要显示的网页:
互联网用:webView.loadUrl("http://www.google.com");
本地文件用:webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放在:assets 文件中
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;
- }
- }
- @Override
- public void onPageStarted(WebView view, String url, Bitmap favicon) {
- Log.i(TAG, "-onPageFinished-" + url);
- if (!progressDialog.isShowing()) { //网页开始加载时,显示进度条。
- progressDialog.show();
- }
- }
- @Override
- public void onPageFinished(WebView view, String url) {
- Log.i(TAG, "-onPageFinished-" + url);
- if (progressDialog.isShowing()) { // 加载完毕后,进度条不显示
- progressDialog.dismiss();
- }
- }
- @Override
- 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) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * json解析
- * @param strJson
- */
- private void parseJson(String strJson){
- try {
- 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) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
看下效果图:
欢迎大家一起学习交流。源码已上传
weibo:http://weibo.com/xzw1989
转载于:https://blog.51cto.com/xuzhiwei/1031871