原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://wangyubin.blog.51cto.com/6807757/1313635

准备,分析:


要做新浪授权重要的是申请到App Key

新浪微博开放平台

新浪微博官方Demo(一定要仔细阅读内涵pdf文件)

 

231700263.jpg

231702346.jpg

以上红色圈中的一定要进行填写,否则会授权失败!app secret的获取可能比较绕一点,但我觉得还是有必要这么做的,具体做法:

1.一定要先把你要授权的用户现在手机上运行一遍,确保手机里有你要授权的用户

2.安装官方的MD5签名生成器,填写包名之后会出现MD5签名之后复制到app secret,附图

232352513.jpg

之后再配置类里面配置相关信息:

232527478.jpg

具体可参考官方提供的demo,再次强调下官方提供的demo不是不能用,只是你的key不对,有很多童鞋瞎抱怨,官方的pdf里面也有详细申请流程,仔细阅读每个细节,别把时间浪费在不必要的事情上,希望这篇文章能对你有所帮助!!!

 

开始,构建 :

 

231308524.jpg

233444495.jpg

//===============本篇文章重点类 SinaAccess

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
 * 新浪微博授权
 * @author Johnny
 *
 */
public class SinaAccess {
               
    private static SinaAccess sinaAccess;
               
    /** 微博API接口类,提供登陆等功能  */
    private Weibo mWeibo;
               
    /** 封装了 "access_token","expires_in","refresh_token",并提供了他们的管理功能  */
    private Oauth2AccessToken mAccessToken;
               
    /** 注意:SsoHandler 仅当sdk支持sso时有效 */
    private SsoHandler mSsoHandler;
               
    /** 上下文*/
    private Activity mContext;
               
    private static Handler mHandler;
               
    private SinaAccess(){
        mWeibo = Weibo.getInstance(AppConfig.APP_KEY, AppConfig.REDIRECT_URL, AppConfig.SCOPE);
    }
               
    public static SinaAccess getInstance(Handler mHandler){
        setmHandler(mHandler);
        if(null==sinaAccess){
            sinaAccess=new SinaAccess();
            return sinaAccess;
        }
        return sinaAccess;
    }
               
               
    public static Handler getmHandler() {
        return mHandler;
    }
               
    public static void setmHandler(Handler mHandler) {
        SinaAccess.mHandler = mHandler;
    }
               
    /**
     * 判断是否授权成功
     */
    public void getAuthorize(Activity mContext){
        // 从 SharedPreferences 中读取上次已保存好 AccessToken 等信息,
        // 第一次启动本应用,AccessToken 不可用
        this.mContext=mContext;
        mAccessToken = AccessTokenKeeper.readAccessToken(mContext);
        if (mAccessToken.isSessionValid()) {
            /*String date = new java.text.SimpleDateFormat("yyyy/MM/dd hh:mm:ss")
                    .format(new java.util.Date(mAccessToken.getExpiresTime()));
            Toast.makeText(mContext, "access_token 仍在有效期内,无需再次登录: \naccess_token:"
                    + mAccessToken.getToken() + "\n有效期:" + date , Toast.LENGTH_SHORT).show();*/
            mHandler.sendEmptyMessage(AppConfig.OAUTH_SUCCEED);
            AccessTokenKeeper.keepAccessToken(mContext, mAccessToken);
        }else{
            Logger.d("授权未找到");
        }
    }
               
    /**
     * 普通授权
     */
    public void authorize(){
        mWeibo.anthorize(mContext, new AuthDialogListener());
    }
               
    /**
     * SSO 授权调用
     */
    public void ssoAuthorize(){
        mSsoHandler = new SsoHandler(mContext, mWeibo);
        mSsoHandler.authorize(new AuthDialogListener(), null);
    }
               
    /**
     * SSO 授权回调    重要:发起 SSO 登陆的Activity必须重写onActivityResult
     * 注:使用SSO登录前,请检查手机上是否已经安装新浪微博客户端,"
                    + "目前仅3.0.0及以上微博客户端版本支持SSO;如果未安装,将自动转为Oauth2.0进行认证
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void  ssoAuthorizeCallBack(int requestCode, int resultCode, Intent data){
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
               
    /**
     * 微博认证授权回调类。
     * 1. SSO登陆时,需要在{@link #onActivityResult}中调用mSsoHandler.authorizeCallBack后,
     *    该回调才会被执行。
     * 2. 非SSO登陆时,当授权后,就会被执行。
     * 当授权成功后,请保存该access_token、expires_in等信息到SharedPreferences中。
     */
    class AuthDialogListener implements WeiboAuthListener {
                   
        @Override
        public void onComplete(Bundle values) {
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            mAccessToken = new Oauth2AccessToken(token, expires_in);
            if (mAccessToken.isSessionValid()) {
                /*String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new java.util.Date(mAccessToken.getExpiresTime()));
                Toast.makeText(mContext, "认证成功: \r\n access_token: " + token + "\r\n" + "expires_in: "
                        + expires_in + "\r\n有效期:" + date , Toast.LENGTH_SHORT).show();*/
                mHandler.sendEmptyMessage(AppConfig.OAUTH_COMPLETE);
                AccessTokenKeeper.keepAccessToken(mContext, mAccessToken);
            }else{
                Logger.d("授权未找到");
            }
        }
        @Override
        public void onError(WeiboDialogError e) {
            Logger.e(e.getMessage());
            /*Toast.makeText(mContext,
                    "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();*/
        }
        @Override
        public void onCancel() {
            Logger.d("Auth cancel");
            /*Toast.makeText(mContext, "Auth cancel", Toast.LENGTH_LONG).show();*/
        }
        @Override
        public void onWeiboException(WeiboException e) {
            Logger.d(e.getMessage());
            /*Toast.makeText(mContext,
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();*/
        }
    }
}

//============================LoginActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
 * 新浪授权登陆页面
 * @author Johnny
 *
 */
public class LoginActivity extends BaseActivity{
                 
    private Button mLoginBtn;
                 
    /**新浪微博授权*/
    private SinaAccess sinaAccess;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }
                 
    private void init(){
        /**新浪微博授权类初始化*/
        sinaAccess=SinaAccess.getInstance(myHandler);
        /**一定要调用该方法(返回是否授权成功)*/
        sinaAccess.getAuthorize(this);
                     
        mLoginBtn=(Button) findViewById(R.id.btn_login);
                     
        mLoginBtn.setOnClickListener(btnOnClickListener());
                     
    }
                 
    private void enter(){
        Intent intent = new Intent(this, KKsinaActivity.class);
        startActivity(intent);
        finish();
    }
    @Override
    protected void getMessage(Message msg) {
        // TODO Auto-generated method stub
        switch (msg.what) {
        case AppConfig.OAUTH_SUCCEED:
            enter();
            break;
        case AppConfig.OAUTH_COMPLETE:
            toastShow("认证成功");
            enter();
            break;
        case AppConfig.OAUTH_ERROR:
        case AppConfig.OAUTH_CANCEL:
        case AppConfig.OAUTH_WEIBO_EXCEPTION:
            toastShow("认证失败,查看Log日志输出具体分析错误");
            break;
        }
        super.getMessage(msg);
    }
                 
    private OnClickListener btnOnClickListener() {
        return new View.OnClickListener() {
                         
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                /*sinaAccess.authorize();//普通授权*/            
                sinaAccess.ssoAuthorize();//SSO 授权
            }
        };
    }
                 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.d("SSO授权返回调用");
        //SSO 授权回调    重要:发起 SSO 登陆的Activity必须重写onActivityResult
        sinaAccess.ssoAuthorizeCallBack(requestCode, resultCode, data);
    }
                 
                 
}

//=====================AppConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
 * 应用配置类
 * @author Johnny
 *
 */
public class AppConfig {
                                                                                
    // 应用的key 请到官方申请正式的appkey替换APP_KEY
//  public static final String APP_KEY      = "1509943602";//公司
    public static final String APP_KEY      = "1452755821";//笔记本
    // 替换为开发者REDIRECT_URL
    public static final String REDIRECT_URL = "http://down.51cto.com/data/983705";
    // 新支持scope:支持传入多个scope权限,用逗号分隔
    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";
    public static final String CLIENT_ID         = "client_id";
    public static final String RESPONSE_TYPE     = "response_type";
    public static final String USER_REDIRECT_URL = "redirect_uri";
    public static final String DISPLAY           = "display";
    public static final String USER_SCOPE        = "scope";
    public