时间:2021-07-01 10:21:17 帮助过:3人阅读
通过上面的代码就可以看出在客户端需要做下面几件事情:
1、对client_id和client_secret进行Base64String编码,在iOS里有专门对NSString进行Base64编码的库,具体请参见NSData+Base64。
2、将grant_type为"client_credentials"作为参数Post给服务器地址;
3、最后需要注意的是AFNetWorking 实现Basic 验证的时候,传值的时候注意Basic后面有一个空格,然后设置Content-Type为"application/x-www-form-urlencoded;charset=UTF-8"。这样就可以拿到access_token。代码如下:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSString *client_id = @"1234"; NSString *client_secret = @"5678"; NSString *authStr = [NSString stringWithFormat:@"%@:%@",client_id,client_secret]; NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; NSString *authValue = [NSString stringWithFormat:@"Basic %@",[authData base64EncodedStringWithOptions:0]]; [manager.requestSerializer setValue:authValue forHTTPHeaderField:@"Authorization"]; [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; NSDictionary *params = @{@"grant_type":@"client_credentials"}; [manager POST:@"http://api.cnblogs.com/token" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", [error description]); }];
这样就完成了本次场景的需求。实验以Basic 验证方式获取access_token。这样拿到服务端的授权以后就可以调用公开的API列表啦。
使用AFNetWorking 实现以Basic Authentication方式获取access-token
标签: