新浪微博授权

关于授权,其实官方的SDK文档写得很详细,我就在这里简要阐述一下步骤,和一些需要注意的地方

PS:大部分内容出自新浪官方SDK文档

一、到新浪开放平台注册成为开发者http://open.weibo.com/

二、因为我们是开发IOS移动应用,所以选择创建应用

创建完后会得到一个App Key 和App Secrect,App Key在后面开发时用来注册应用,后者我目前还没用到 ,以后知道了来补充

三、创建完毕,到管理中心,编辑刚刚创建的应用,这里需要注意这几点

1、应用信息--基本信息:这里需要自己添加Apple ID和Bundle ID,Apple ID可以先随便填,对开发没影响,Bundle ID必须确保与你建的工程的Bundle Identifier一致,也就是说,以后建了工程,工程的Bundle Identifier 必须得按这个来填

2、应用信息--高级信息:这里要修改一下授权回调页,因为我们是应用,没有回调页,这里就填默认页为https://api.weibo.com/oauth2/default.html

四、接着创建我们的工程,这里工程需要修改两个地方:

1、这个要确保和之前的Bundle ID一致


2、选择Info页面,到最下面的URL Types,IdentifIer这样填即可,URL Schemes要填写成 wb+App Key,注意要填写正确,不然调不到授权页,会闪退。


3、从新浪开放平台上下IOS-SDK包下来,导入到我们的工程里,包含SDK的头文件,这里我是按照官方demo的做法,在Supporting Files\MySinaWeibo-Prefix.pch文件里面声明,然后把AppKey 和 RedirectURI定义出来

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #ifdef __OBJC__  
  2.     #import <UIKit/UIKit.h>  
  3.     #import <Foundation/Foundation.h>  
  4.   
  5. #import "WeiboSDK.h"  
  6.   
  7. #define kAppKey         @"233113133"  
  8. #define kRedirectURI    @"https://api.weibo.com/oauth2/default.html"  
  9. #endif  

4、回到AppDelegate.h文件,添加委托

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @interface AppDelegate : UIResponder <UIApplicationDelegate,WeiboSDKDelegate>  

5、到AppDelegate.m文件,注册应用

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  2. {  
  3.     [WeiboSDK enableDebugMode:YES];  //打开调试选项  
  4.     [WeiboSDK registerApp:kAppKey];  //注册应用  
  5.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
  6.     // Override point for customization after application launch.  
  7.     self.window.backgroundColor = [UIColor whiteColor];  
  8.     [self.window makeKeyAndVisible];    LoginViewController *rootViewRootController = [[LoginViewController alloc] init];  
  9.     self.window.rootViewController = rootViewRootController;  
  10.     LoginViewController *rootViewRootController = [[LoginViewController alloc] init];  
  11.     self.window.rootViewController = rootViewRootController;  
  12.     return YES;  
  13. }  
重写AppDelegate的openURL方法

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation  
  2. {  
  3.     return [WeiboSDK handleOpenURL:url delegate:self];  
  4. }  
6、到LoginView.m文件,要请求授权认证只需下面四行代码

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. WBAuthorizeRequest *request = [WBAuthorizeRequest request];  
  2. request.redirectURI = kRedirectURI;  
  3. request.scope = @"all";  
  4. [WeiboSDK sendRequest:request];  
这里会给服务器发一个请求,我们回到AppDelegate.m文件,添加下面两个委托方法

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #pragma mark - WeiboSDK delegate  
  2.   
  3. - (void)didReceiveWeiboRequest:(WBBaseRequest *)request  
  4. {  
  5.       
  6. }  
  7.   
  8. - (void)didReceiveWeiboResponse:(WBBaseResponse *)response  
  9. {  
  10.     if ([response isKindOfClass:WBAuthorizeResponse.class])  
  11.     {  
  12.         wbtoken = [(WBAuthorizeResponse *)response accessToken];  
  13.         userId = [(WBAuthorizeResponse * )response userID];  
  14.         NSLog(@"userid : %@",userId);  
  15.         [[NSUserDefaults standardUserDefaults] setObject:wbtoken forKey:@"access_token"];  
  16.         [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userID"];  
  17.         [[NSUserDefaults standardUserDefaults] synchronize];  
  18.     }  
  19. }  
第一个是收到服务器的请求时会调用这个方法,第二个是收到服务器回复的时候会调用的,这里我们发送了请求,服务器会给回复,所以调用下面的方法,我们先判断回复是不是授权认证类的,是的话,就取到accessToken值和userID值,这两个值很重要,accessToken是后面我们调用API时要用的参数,userID可以用来获取我们的用户信息,后面三行是将这两个值保存到应用里,这是一种轻量级本地存储,这样不用每次都要授权,只要将上面的授权请求修改一下,这样:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if ([[NSUserDefaults standardUserDefaults] objectForKey:@"access_token"] == nil) {  
  2.     WBAuthorizeRequest *request = [WBAuthorizeRequest request];  
  3.     request.redirectURI = kRedirectURI;  
  4.     request.scope = @"all";  
  5.     [WeiboSDK sendRequest:request];  
  6. }  
好,大功告成,现在运行,应该能跳转到授权页面了,要确保模拟器能上网哦,亲~~
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/** * 测试新浪微博API * @author syn * @date 2010/12/22 */ public class TestActivity extends Activity { private static final String BASE_URL = "http://api.t.sina.com.cn/"; //API接口 private static final String CONSUMER_KEY = "270793661"; //你申请的Key private static final String HEADER_AUTHO = "Authorization"; //Authorization private static final String HEADER_BASIC = "Basic "; //Basic private static final String ERROR = "MyError"; //错误 List<myTest> myTestList; /** * 测试用的类,用于解析JSON,因为只是测试,所以乱写一下 */ public class myTest { private Date created_at; //返回微博发布的时间 private String text; //微博内容 private User user; //微博用户信息 public myTest(JSONObject object) throws JSONException //解析JSON文件 { text=""; user=null; created_at=new Date(object.getString("created_at")); text=object.getString("text"); user=new User(object.getJSONObject("user")); } } @Override public void onCreate(Bundle savedInstanceState) { String tailUrl="statuses/public_timeline.json"; //我要获得的是最新的公共微博 String response=getResponse(tailUrl, MainActivity.loginUser);//调用提交函数,此函数是核心部分 super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.test); TextView textView01=(TextView)findViewById(R.id.test); if(response.startsWith(ERROR)) textView01.setText("error"); else { JSONArray array; try { array = new JSONArray(response); for (int i = 0; i < array.length(); i++) { myTest mytest= new myTest(array.getJSONObject(i)); //myTestList.add(mytest); String content="Content:"+mytest.text+" Author:"+mytest.user.getNike()+" Date:"+mytest.created_at; textView01.setText(content); } } catch (JSONException e) { e.printStackTrace(); } } } /** * 此函数提交URL,返回访问结果 * @param tailUrl json或者xml的url * @param user 用户的一个对象 * @return 提交结果 */ private static String getResponse(String tailUrl,User user) { String httpUrl=BASE_URL+tailUrl; ArrayList<NameValuePair> postParams=new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair("source",CONSUMER_KEY)); //封装入APP Key try { HttpPost httpRequest = new HttpPost(httpUrl); httpRequest.setEntity(new UrlEncodedFormEntity(postParams,HTTP.UTF_8)); //把参数放入Entity httpRequest.addHeader(HEADER_AUTHO, HEADER_BASIC+user.encodeBase64NamePass()); //这里就是给用户的用户名和密码加密,然后放入http头 httpRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false); HttpClient httpclient = new DefaultHttpClient(); HttpResponse httpResponse = httpclient.execute(httpRequest); //提交 int statusCode=httpResponse.getStatusLine().getStatusCode(); //获得结果码200是正确 if ( statusCode== HttpStatus.SC_OK) { String strResult = EntityUtils.toString(httpResponse.getEntity()); Log.e("WeiboKu", "strResult :"+strResult); return strResult; } else { Log.e("WeiboKu", "strResult Error:"+statusCode); return ERROR+String.valueOf(statusCode); } } catch (Exception e) { Log.e("WeiboKu", "getResponse Exception:"+e.getMessage()); return ERROR+e.getMessage().toString(); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值