JSON和HTTP 開源框架使用:Fastjson 和Aysnc-Http
第一步:去對應的平臺上註冊app的相關信息,這一步,可參考我的另外一個篇,關於加入親加通訊雲的文章
各個平臺註冊應用信息的地址如下:
新浪微博 http://open.weibo.com
騰訊微博 http://dev.t.qq.com
QQ空間 http://connect.qq.com/intro/login/
微信好友 http://open.weixin.qq.com
Facebook https://developers.facebook.com
Twitter https://dev.twitter.com
人人網 http://dev.renren.com
開心網 http://open.kaixin001.com
搜狐微博 http://open.t.sohu.com
網易微博 http://open.t.163.com
豆瓣 http://developers.douban.com
有道雲筆記 http://note.youdao.com/open/developguide.html#app
印象筆記 https://dev.evernote.com/
Linkedin https://www.linkedin.com/secure/developer?newapp=
FourSquare https://developer.foursquare.com/
搜狐隨身看 https://open.sohu.com/
Flickr http://www.flickr.com/services/
Pinterest http://developers.pinterest.com/
Tumblr http://www.tumblr.com/developers
Dropbox https://www.dropbox.com/developers
Instagram http://instagram.com/developer#
VKontakte http://vk.com/dev
新浪微博登錄:
- <!-- 微博 -->
- <!-- 必須註冊在微博授權,分享微博時候用到 -->
- <activity
- android:name= "com.sina.weibo.sdk.component.WeiboSdkBrowser"
- android:configChanges= "keyboardHidden|orientation"
- android:exported= "false"
- android:windowSoftInputMode="adjustResize" >
- </activity >
- <service
- android:name= "com.sina.weibo.sdk.net.DownloadService"
- android:exported= "false" >
- </service >
3、java代碼中登錄
- //註冊成功之後的APPKEY
- public static final String SINA_APPKEY = "2651314935";
- //註冊成功之後的REDIRECT_URL
- public static final String SINA_REDIRECT_URL = "https://api.weibo.com/oauth2/default.html" ;
- public static final String SINA_SCOPE = "all";
- /** 注意:SsoHandler 僅當 SDK 支持 SSO 時有效 */
- private SsoHandler mSsoHandler;
- private AuthInfo mAuthInfo;
- private Oauth2AccessToken mAccessToken;
- mAuthInfo = new AuthInfo(LoginActivity. this,
- APPConstants. SINA_APPKEY, APPConstants.SINA_REDIRECT_URL ,
- APPConstants. SINA_SCOPE);
- mSsoHandler = new SsoHandler(LoginActivity. this, mAuthInfo);
- mSsoHandler.authorize( new AuthListener());
- /******************************** 微博回調 ***********************************************/
- /**
- * 微博認證授權回調類。 1. SSO 授權時,需要在 {@link #onActivityResult} 中調用
- * {@link SsoHandler#authorizeCallBack} 後, 該回調纔會被執行。 2. 非 SSO
- * 授權時,當授權結束後,該回調就會被執行。 當授權成功後,請保存該 access_token、expires_in、uid 等信息到
- * SharedPreferences 中。
- */
- public class AuthListener implements WeiboAuthListener {
- @Override
- public void onComplete(Bundle values) {
- // 從 Bundle 中解析 Token
- mAccessToken = Oauth2AccessToken.parseAccessToken(values);
- if ( mAccessToken.isSessionValid()) {
- MyProgressDialog. showDialogWithFalse(LoginActivity.this, "登陸",
- "正在獲取用戶信息" );
- thirdUser = new ThirdUserInfo();
- thirdUser.setThirdID( mAccessToken.getUid()); //mAccessToken.getUid() ,獲取到UID,作爲身份的唯一標示
- UsersAPI mUsersAPI = new UsersAPI(LoginActivity.this,APPConstants.SINA_APPKEY , mAccessToken );
- long uid = Long.parseLong(mAccessToken.getUid());
- mUsersAPI.show(uid, mListener); //獲取用戶基本信息
- } else {
- // 以下幾種情況,您會收到 Code:
- // 1. 當您未在平臺上註冊的應用程序的包名與簽名時;
- // 2. 當您註冊的應用程序包名與簽名不正確時;
- // 3. 當您在平臺上註冊的包名和簽名與您當前測試的應用的包名和簽名不匹配時。
- // String code = values.getString("code");
- }
- }
- @Override
- public void onCancel() {
- }
- @Override
- public void onWeiboException(WeiboException e) {
- }
- }
- //獲取用戶信息的回調
- private RequestListener mListener = new RequestListener() {
- @Override
- public void onComplete(String response) {
- if (!TextUtils. isEmpty(response)) {
- // 調用 User#parse 將JSON串解析成User對象,所有的用戶信息全部在這裏面
- User user = User. parse(response);
- thirdUser.setNickName(user. name); // 暱稱
- thirdUser.setIcon(user. avatar_hd); // 頭像
- thirdUser.setGender(user. gender.equals( "m") ? "男" : "女" );
- ThirdUserVerify. verifyUser(LoginActivity.this, thirdUser, 2);
- }
- }
- @Override
- public void onWeiboException(WeiboException e) {
- MyProgressDialog. closeDialog();
- ErrorInfo info = ErrorInfo. parse(e.getMessage());
- ToastUtil. showShort(LoginActivity.this, info.toString());
- }
- };
- @Override
- protected void onActivityResult( int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if ( mSsoHandler != null) {
- mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
- }
- }
微信登錄
- BaseApplication. mIwapi = WXAPIFactory.createWXAPI( LoginActivity. this, APPConstants.WX_APPID, true );
- BaseApplication. mIwapi.registerApp(APPConstants. WX_APPID);
- SendAuth.Req req = new SendAuth.Req();
- req. scope = "snsapi_userinfo";
- req. state = "wechat_sdk_demo_test";
- BaseApplication. mIwapi.sendReq(req);//執行完畢這句話之後,會在WXEntryActivity回調
- public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
- private Bundle bundle;
- //這個實體類是我自定義的實體類,用來保存第三方的數據的實體類
- private ThirdUserInfo info= null;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- AppManager. getAppManager().addActivity(WXEntryActivity. this);
- BaseApplication. mIwapi.handleIntent(getIntent(), WXEntryActivity.this); //必須調用此句話
- }
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- BaseApplication. mIwapi.handleIntent(intent, WXEntryActivity.this);//必須調用此句話
- }
- @Override
- public void onReq(BaseReq req) {
- System. out.println();
- }
- /**
- * Title: onResp
- *
- * API:https://open.weixin.qq.com/ cgi- bin/showdocument ?action=dir_list&t=resource/res_list&verify=1&id=open1419317853 &lang=zh_CN
- * Description:在此處得到Code之後調用https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
- * 獲取到token和openID。之後再調用https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID 獲取用戶個人信息
- *
- * @param arg0
- * @see com.tencent.mm.sdk.openapi.IWXAPIEventHandler#onResp(com.tencent.mm.sdk.openapi.BaseResp)
- */
- @Override
- public void onResp(BaseResp arg0) {
- bundle=getIntent().getExtras();
- SendAuth.Resp resp = new SendAuth.Resp( bundle);
- //獲取到code之後,需要調用接口獲取到access_token
- if (resp. errCode == BaseResp.ErrCode. ERR_OK) {
- String code = resp. token;
- if(BaseApplication. isWxLogin){
- getToken(code);
- } else{
- WXEntryActivity. this.finish();
- }
- } else{
- WXEntryActivity. this.finish();
- }
- }
- //這個方法會取得accesstoken 和openID
- private void getToken(String code){
- MyProgressDialog. showDialog(WXEntryActivity.this, "登陸", "正在獲取用戶信息" );
- HttpBase. get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd7673d08f6c1963d&secret=223d726f966031f30125d0e4e7d4aed3&code=" +code+"&grant_type=authorization_code" , new JsonHttpResponseHandler(){
- @Override
- public void onSuccess( int statusCode, JSONObject response) {
- super.onSuccess(statusCode, response);
- info = new ThirdUserInfo();
- info.setThirdID(response.optString( "openid"));
- getUserInfo(response.optString( "access_token"),response.optString( "openid"));
- }
- @Override
- public void onFailure( int statusCode, Throwable e,
- JSONObject errorResponse) {
- // TODO Auto-generated method stub
- super.onFailure(statusCode, e, errorResponse);
- MyProgressDialog. closeDialog();
- HttpBase. onFailureTips(WXEntryActivity.this, errorResponse);
- }
- });
- }
- //獲取到token和openID之後,調用此接口得到身份信息
- private void getUserInfo(String token,String openID){
- HttpBase. get("https://api.weixin.qq.com/sns/userinfo?access_token=" +token+"&openid=" +openID, new JsonHttpResponseHandler(){
- @Override
- public void onSuccess( int statusCode, JSONObject response) {
- super.onSuccess(statusCode, response);
- info.setNickName(response.optString( "nickname"));
- info.setGender(response.optInt( "sex")==1? "男": "女");
- info.setIcon(response.optString( "headimgurl"));
- ThirdUserVerify. verifyUser(WXEntryActivity.this, info, 3);
- // AppManager.getAppManager().finishActivity(LoginActivity.class);
- }
- @Override
- public void onFailure( int statusCode, Throwable e,
- JSONObject errorResponse) {
- super.onFailure(statusCode, e, errorResponse);
- MyProgressDialog. closeDialog();
- HttpBase. onFailureTips(WXEntryActivity.this, errorResponse);
- }
- });
- }
- }
QQ登錄
1、註冊APPKEY- <!-- QQ -->
- <activity
- android:name= "com.tencent.tauth.AuthActivity"
- android:launchMode= "singleTask"
- android:noHistory= "true" >
- <intent-filter >
- <action android:name ="android.intent.action.VIEW" />
- <category android:name ="android.intent.category.DEFAULT" />
- <category android:name= "android.intent.category.BROWSABLE" />
- <data android:scheme ="1104406273" />
- </intent-filter >
- </activity >
- <activity
- android:name= "com.tencent.connect.common.AssistActivity"
- android:configChanges="orientation|keyboardHidden|screenSize"
- android:theme= "@android:style/Theme.Translucent.NoTitleBar" />
- <span style="white-space:pre"> </span>
- //初始化Tencent
- public Tencent mTencent = Tencent.createInstance(APPConstants. QQ_APPID,LoginActivity.this);
- // QQ發起登陸
- mTencent.login(LoginActivity. this, "all", new IUiListener() {
- @Override
- public void onCancel() {
- }
- @Override
- public void onComplete(Object arg0) {
- //登陸成功的回調,在此處可以獲取用戶信息
- MyProgressDialog. showDialogWithFalse(LoginActivity.this, "登陸", "正在獲取用戶信息" );
- initOpenidAndToken((JSONObject) arg0);
- updateUserInfo();
- }
- @Override
- public void onError(UiError arg0) {
- }
- });
- /**
- * @Title: initOpenidAndToken
- * @Description: 初始化OPENID以及TOKEN身份驗證。
- * @param @param jsonObject
- * @return void
- * @throws
- */
- private void initOpenidAndToken (JSONObject jsonObject) {
- thirdUser = new ThirdUserInfo();
- try {
- //這裏的Constants類,是 com.tencent.connect.common.Constants類,下面的幾個參數也是固定的
- String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN );
- String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN );
- //OPENID,作爲唯一身份標識
- String openId = jsonObject.getString(Constants.PARAM_OPEN_ID );
- if (!TextUtils. isEmpty(token) && !TextUtils.isEmpty(expires)&& !TextUtils. isEmpty(openId)) {
- //設置身份的token
- mTencent.setAccessToken(token, expires);
- mTencent.setOpenId(openId);
- thirdUser.setThirdID(openId);
- }
- } catch (Exception e) {
- }
- }
- /**
- * @Title: updateUserInfo
- * @Description: 在回調裏面可以獲取用戶信息數據了
- * @param
- * @return void
- * @throws
- */
- private void updateUserInfo() {
- if ( mTencent != null && mTencent.isSessionValid()) {
- UserInfo mInfo = new UserInfo(LoginActivity. this, mTencent.getQQToken());
- mInfo.getUserInfo(listener);
- IUiListener listener = new IUiListener() {
- @Override
- public void onError(UiError e) {
- MyProgressDialog. closeDialog();
- }
- // 用戶的信息回調在此處
- @Override
- public void onComplete( final Object response) {
- // 返回Bitmap對象。
- try {
- JSONObject obj = new JSONObject(response.toString());
- thirdUser.setNickName(obj.optString( "nickname"));
- thirdUser.setIcon(obj.optString( "figureurl_qq_2"));
- thirdUser.setGender(obj.optString( "gender"));
- ThirdUserVerify. verifyUser(LoginActivity.this,thirdUser, 1);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onCancel() {
- MyProgressDialog. closeDialog();
- }
- };
- }
- }