安卓微博登录第三方详解

前言:QQ、微信都有了、自然少不了微博,接着上一篇

1、效果图
在这里插入图片描述

2、微博开放平台 http://open.weibo.com/
创建应用填入信息
点开我的应用>应用基本信息

在这里插入图片描述
填入包名与签名即可,注意:应用未上线可以先填测试地址(例:蒲公英下载链接)或公司官网等,在提交审核通过即可。

3、资源引入
主项目build.gradle中添加:在这里插入图片描述
maven { url ‘https://dl.bintray.com/thelasterstar/maven/’ }

app build.gradle中添加:

implementation 'com.sina.weibo.sdk:core:4.3.1:openDefaultRelease@aar'//微博SDK
implementation 'com.squareup.okhttp3:okhttp:3.4.1'//网络请求
implementation 'com.github.bumptech.glide:glide:4.7.1'//图片加载

4、代码部分

在自定义Application类中初始化weiboSDK,这里是直接在Activity中初始化

public class MainActivity extends AppCompatActivity {

    /**
     * 当前 DEMO 应用的 APP_KEY,第三方应用应该使用自己的 APP_KEY 替换该 APP_KEY
     */
    public static final String APP_KEY = "2850806666";

    /**
     * 当前 DEMO 应用的回调页,第三方应用可以使用自己的回调页。
     * 建议使用默认回调页:https://api.weibo.com/oauth2/default.html
     */
    public static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";

    /**
     * WeiboSDKDemo 应用对应的权限,第三方开发者一般不需要这么多,可直接设置成空即可。
     */
//    public static final String SCOPE =
//            "email,direct_messages_read,direct_messages_write,"
//                    + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
//                    + "follow_app_official_microblog," + "invitation_write";

    private SsoHandler ssoHandler;

    private ImageView weiboPic;
    private TextView weiboName, weiboJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        weiboPic = this.findViewById(R.id.weibo_pic);
        weiboName = this.findViewById(R.id.weibo_name);
        weiboJson = this.findViewById(R.id.weibo_json);

        //新浪微博初始化,对应的参数分别是app_key,回调地址,和权限
        AuthInfo mAuthInfo = new AuthInfo(this, APP_KEY,
                REDIRECT_URL, "");
        WbSdk.install(this, mAuthInfo);
        ssoHandler = new SsoHandler(this);

        //微博授权事件
        findViewById(R.id.weibo_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WbAuthUtils.startSinaWeiBo(ssoHandler);
            }
        });
        WbAuthUtils utils = new WbAuthUtils();
        utils.setListener(new WbAuthUtils.onSuccessListener() {
            @Override
            public void onSuccess(final String result, final String icon, final String name) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //头像
                       Glide.with(MainActivity.this).load(icon).into(weiboPic);
                        //昵称
                        weiboName.setText(name);
                        //json数据
                        weiboJson.setText(result);
                    }
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                //登录失败
                Toast.makeText(Main2Activity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * SSO 授权回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 重要:发起 SSO 登陆的 Activity 必须重写 onActivityResults
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}

回调工具类

public class WbAuthUtils {

    private static final String TAG = "WbAuthUtils";

    private static final String WEIBO_USERINFO_URL = "https://api.weibo.com/2/users/show.json?access_token=";//微博个人信息链接

    /**
     * 封装了 "access_token","expires_in","refresh_token",并提供了他们的管理功能
     */
    private static Oauth2AccessToken mAccessToken;

    /**
     * 开启微博授权登录
     */
    public static void startSinaWeiBo(SsoHandler ssoHandler) {

        //授权方式有三种,第一种对客户端授权 第二种对Web短授权,第三种结合前两中方式
        ssoHandler.authorize(new WbAuthListener() {
            @Override
            public void onSuccess(Oauth2AccessToken token) {

                Log.e(TAG, "onSuccess: " + token.getToken());
                Log.e(TAG, "onSuccess: " + token.getUid());

                mAccessToken = token;
                //Session是否过期
                if (mAccessToken.isSessionValid()) {
                    getSinaWeiBoInfo(token.getToken(), token.getUid());
                }
            }

            @Override
            public void cancel() {
                Log.e(TAG, "微博授权取消: ");
            }

            @Override
            public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
                Log.e(TAG, "微博授权失败: ");
            }
        });
    }


    /**
     * 获取微博信息
     */
    private static void getSinaWeiBoInfo(String token, String uid) {

        String url = WEIBO_USERINFO_URL + token + "&uid=" + uid;
        
        Log.e(TAG, "请求token: " + token);
        Log.e(TAG, "请求openId: " + uid);

        Request request = new Request.Builder().url(url).build();
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //成功回调
                String result = response.body().string();

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String name = jsonObject.getString("name");
                    String icon = jsonObject.getString("profile_image_url");
                    
                    Log.e(TAG, "result: "+ result);
                    Log.e(TAG, "name: "+ name);
                    Log.e(TAG, "icon: "+ icon);

                    listener.onSuccess(result, icon, name);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static onSuccessListener listener;

    public void setListener(onSuccessListener listener) {
        this.listener = listener;
    }

    public interface onSuccessListener {

        void onSuccess(String result, String icon, String name);//json数据、头像、名字

        void onFailure(String errorMessage);//错误信息
    }
}

对应布局文件

<?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"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingTop="30dp">

    <ImageView
        android:id="@+id/weibo_pic"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/weibo_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="微博姓名"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/weibo_json"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:maxLength="1000"
        android:padding="5dp"
        android:text="JSON数据"
        android:textSize="12sp" />

    <Button
        android:id="@+id/weibo_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="微博登录" />

</LinearLayout>

5、返回数据

可以看到微博返回的数据是非常多的差不多有120行左右~

在这里插入图片描述

最后附上github链接: https://github.com/sinaweibosdk/weibo_android_sdk

猜你喜欢

转载自blog.csdn.net/qq_34536167/article/details/83745632