当前位置: 移动技术网 > IT编程>移动开发>Android > Android仿新浪微博oauth2.0授权界面实现代码(2)

Android仿新浪微博oauth2.0授权界面实现代码(2)

2019年07月24日  | 移动技术网IT编程  | 我要评论

南京地下摄影棚,骑士夺冠赌城疯玩,父亲击落无人机

oauth2.0授权界面,大致流程图:

前提准备:

在新浪开放平台申请appkey和appsecret:.
熟悉oauth2.0协议,相关知识:
oauth2的access_token接口:

代码详解

大致思路如下:建立一个webview加载授权界面,授权回调地址请参考constants.java里面有详细注解。页面加载时会回调该方法,如果用户同意(输入自己微博的账号密码)就会成功获取code然后发送一个异步的post请求获access_token 若成功获取access_token信息,则使用sharedpreferences保存所有重要信息,并跳转到主界面。
异步的post设置的请求参数必须跟oauth2的access_token接口里要求的请求参数一一对应。
这里获取的access_token是后来每个接口的必备请求参数。

**
 * 自定义授权界面,申请令牌
 */
public class oauthactivity extends activity {
 //保存数据信息
 private sharedpreferences preferences;
 private static final string tag = "oauthactivity";
 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.webview);
  //获取只能被本程序读写的sharedpreferences对象
  preferences = getsharedpreferences("oauth2.0", context.mode_private);
  //webview加载回调页
  webview webview = (webview) findviewbyid(r.id.webview);
  //管理webview
  websettings websettings = webview.getsettings();
  //启用javascript调用功能
  websettings.setjavascriptenabled(true);
  //启用缩放网页功能
  websettings.setsupportzoom(true);
  //获取焦点
  webview.requestfocus();
  //判断网络连接状态,无网络则去设置网络,有网则继续
  string url = constants.url;
  webview.loadurl(url);
  //webviewclient主要帮助webview处理各种通知、请求事件
  webviewclient client = new webviewclient() {
   /**
    * 页面加载时会回调该方法,如果用户同意就会成功获取code
    * 然后发送一个异步的post请求获取access_token
    * 若成功获取access_token信息,则保存所有重要信息
    * 并跳转到主界面
    * @param view 显现界面视图
    * @param url 加载网址
    * @param favicon 网址的相关图标
    */
   @override
   public void onpagestarted(webview view, string url, bitmap favicon) {
    if (url.startswith(constants.redirect_url)) {
     string code = url.split("=")[1];
     //设置请求参数
     requestparams params = new requestparams();
     params.put("client_id", constants.client_id);
     params.put("client_secret", constants.app_secret);
     params.put("grant_type", "authorization_code");
     params.put("redirect_uri", constants.redirect_url);
     params.put("code", code);
     //发送异步post请求access_token令牌,并保存的oathu的
     // client_id和client_secret和access_token等重要信息
     weiborestclient.post("oauth2/access_token", params, new asynchttpresponsehandler() {
      @override
      public void onsuccess(int i, header[] headers, byte[] bytes) {
       string data = new string(bytes);
       try {
        //服务器返回数据
        jsonobject object = new jsonobject(data);
        (preferences.edit()).clear();
        savedata(object);
        toast.maketext(oauthactivity.this, "登陆成功", toast
          .length_short).show();
        //进入微博主界面
        intent intent = new intent(oauthactivity.this,mainactivity.class);
        startactivity(intent);
        //关闭授权界面
        oauthactivity.this.finish();
       } catch (jsonexception e) {
        e.printstacktrace();
       } }
      @override
      public void onfailure(int i, header[] headers, byte[] bytes, throwable throwable) {
       toast.maketext(oauthactivity.this, "登陆失败", toast.length_short)
         .show();
       oauthactivity.this.finish();
      }});}}};
  webview.setwebviewclient(client);
 }

 /**
  * 使用sharedpreferences保存的oathu的client_id和client_secret和access_token等重要信息
  */
 private void savedata(jsonobject object) {
  try {
   sharedpreferences.editor editor = preferences.edit();
   editor.putstring("access_token", object.getstring("access_token"));
   editor.putstring("remind_in", object.getstring("remind_in"));
   editor.putstring("expires_in", object.getstring("expires_in"));
   editor.putstring("uid", object.getstring("uid"));
   editor.putstring("client_id", constants.client_id);
   editor.putstring("redirect_uri", constants.redirect_url);
   editor.putstring("client_secret", constants.app_secret);
   editor.apply();
  } catch (jsonexception e) {
   e.printstacktrace();
  } }}

这里的异步请求类weiborestclient.java,使用异步发送http请求,在回调函数中处理响应http请求过程不在ui线程进行使用线程池来管理并发数支持get/post请求

public class weiborestclient {
 private static final string base_url = "https://api.weibo.com/";
 private static asynchttpclient client = new asynchttpclient();
 public static void get(string url, requestparams params, asynchttpresponsehandler responsehandler) {
  client.get(getabsoluteurl(url), params, responsehandler);
 }
 public static void post(string url, requestparams params, asynchttpresponsehandler responsehandler) {
   client.post(getabsoluteurl(url), params, responsehandler);
 }
 private static string getabsoluteurl(string relativeurl) {
  return base_url + relativeurl;
 }
}

oauthactivity的布局webview.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

 <webview
  android:id="@+id/webview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>
</linearlayout>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网