HarmonyOS微博第三方登录实现

前方就是光明 2021-09-28 13:48:16 4087


前期准备

在微博开放平台注册一个网站应用,微博开放平台地址如下:

https://open.weibo.com/connect

进入正题

①创建一个登录页面的 Ability

因为使用的是网站接入的方式,所以登录使用 WebView 来实现。

登录页布局文件:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">

<ohos.agp.components.webengine.WebView
    ohos:id="$+id:WebView_weibologin"
    ohos:height="match_parent"
    ohos:width="match_parent"/>

②在登录页 AbilitySlice 中对 WebView 进行设置。

public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_wei_bo_login);

    WebView myWebView = (WebView) findComponentById(ResourceTable.Id_WebView_weibologin);
    myWebView.getWebConfig().setJavaScriptPermit(true);

//自定义WebAgent 用于登录的相关操作
    myWebView.setWebAgent(new WebAgent(){

// isNeedLoadUrl 当WebView即将打开一个链接时会调用此方法 
        @Override
        public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
    // request.getRequestUrl().toString().startsWith("sinaweibo") 
    // 当请求链接为sinaweibo开头(点击网页上一键登录会唤起微博客户端)时,使用下面的方法唤起微博客户端。
            if (request.getRequestUrl().toString().startsWith("sinaweibo")){
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setUri(Uri.parse(request.getRequestUrl().toString()));
                intent.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
                startAbility(intent);
                return false;
            }

    // 当在微博客户端授权后,会重定向至定义的网址,示例中重定向至https://api.dsttl3.cn/?code=【code的值】 ,这时候就可以从链接中获取到code进行下一步了。这里把code传入下个页面
            if (request.getRequestUrl().toString().startsWith("https://api.dsttl3.cn)){
                String code = request.getRequestUrl().toString().substring(28);
                Intent intent = new Intent();
    //  在intent中带上code
                intent.setParam("code",code);
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("cn.dsttl3.dome.weibologin")
                        .withAbilityName("cn.dsttl3.dome.weibologin.MyAbility")
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
    // 结束当前Ability
                terminateAbility();
            }
            return true;
        }
    });
    //授权连接,需要自己修改
    myWebView.load("https://api.weibo.com/oauth2/authorize?client_id=2593566539&response_type=code&forcelogin=false&scope=all&redirect_uri=https%3A%2F%2Fapi.dsttl3.cn");
}

③获取到 code 后,在 MyAbility 中获取微博 token。

public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_my);
Text text = (Text) findComponentById(ResourceTable.Id_text_helloworld);
String code = intent.getStringParam("code");
new Thread(new Runnable() {
@Override
public void run() {
try {
String YOUR_CLIENT_ID = "2593566539";
String YOUR_CLIENT_SECRET = "383fc6262e954e18f5b7efe3c9899284";
String YOUR_REGISTERED_REDIRECT_URI = "https://api.dsttl3.cn";
String ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
OkHttpClient client = new OkHttpClient();
FormBody body = new FormBody.Builder()
.add("client_id", YOUR_CLIENT_ID)
.add("client_secret", YOUR_CLIENT_SECRET)
.add("grant_type", "authorization_code")
.add("redirect_uri", YOUR_REGISTERED_REDIRECT_URI)
.add("code", code).build();
Request okRequest = new Request.Builder().url(ACCESS_TOKEN_URL).header("referer",YOUR_REGISTERED_REDIRECT_URI).post(body).build();
Call call = client.newCall(okRequest);
Response re = call.execute();
String s = re.body().string();
Gson gson = new Gson();
WeiBoTokenJson w = gson.fromJson(s, WeiBoTokenJson.class);
getUITaskDispatcher().asyncDispatch(new Runnable() {
@Override
public void run() {
text.setText("登录成功:token=" + w.getAccess_token());
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

获取微博 Token 完成。

效果演示如下:

了解更多请下载源代码:

https://gitee.com/dsttl3/WeiBoLogin

来源:鸿蒙技术社区

声明:本文内容由易百纳平台入驻作者撰写,文章观点仅代表作者本人,不代表易百纳立场。如有内容侵权或者其他问题,请联系本站进行删除。
红包 94 收藏 评论 打赏
评论
0个
内容存在敏感词
手气红包
    易百纳技术社区暂无数据
相关专栏
置顶时间设置
结束时间
删除原因
  • 广告/SPAM
  • 恶意灌水
  • 违规内容
  • 文不对题
  • 重复发帖
打赏作者
易百纳技术社区
前方就是光明
您的支持将鼓励我继续创作!
打赏金额:
¥1易百纳技术社区
¥5易百纳技术社区
¥10易百纳技术社区
¥50易百纳技术社区
¥100易百纳技术社区
支付方式:
微信支付
支付宝支付
易百纳技术社区微信支付
易百纳技术社区
打赏成功!

感谢您的打赏,如若您也想被打赏,可前往 发表专栏 哦~

举报反馈

举报类型

  • 内容涉黄/赌/毒
  • 内容侵权/抄袭
  • 政治相关
  • 涉嫌广告
  • 侮辱谩骂
  • 其他

详细说明

审核成功

发布时间设置
发布时间:
是否关联周任务-专栏模块

审核失败

失败原因
备注
拼手气红包 红包规则
祝福语
恭喜发财,大吉大利!
红包金额
红包最小金额不能低于5元
红包数量
红包数量范围10~50个
余额支付
当前余额:
可前往问答、专栏板块获取收益 去获取
取 消 确 定

小包子的红包

恭喜发财,大吉大利

已领取20/40,共1.6元 红包规则

    易百纳技术社区