// // OauthViewController.m // WPWEIBO // // Created by apple on 15/5/12. // Copyright (c) 2015年 apple. All rights reserved. // #import "OauthViewController.h" @interface OauthViewController () <UIWebViewDelegate,NSURLConnectionDataDelegate> @end @implementation OauthViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. NSString *urlstr = @"https://api.weibo.com/oauth2/authorize?client_id=4293602466&redirect_uri=http://www.baidu.com"; NSURL *url = [NSURL URLWithString:urlstr]; UIWebView *uiw1 = [[UIWebView alloc] init]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; [uiw1 loadRequest:req ]; uiw1.frame = self.view.bounds; [self.view addSubview:uiw1]; uiw1.delegate = self; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *url = request.URL.absoluteString; // NSLog(@"%@",url); NSRange range = [url rangeOfString:@"code="]; NSLog(@"%@",NSStringFromRange(range)); if (range.length != 0) { NSString *code = [url substringFromIndex:(int)(range.location + range.length)]; [self getToken:code]; } return YES; } - (void)getToken:(NSString *)code { /* https://api.weibo.com/oauth2/access_token HTTP请求方式 POST 请求参数 必选类型及范围说明 client_id truestring 申请应用时分配的AppKey。 client_secret truestring 申请应用时分配的AppSecret。 grant_type truestring 请求的类型,填写authorization_code grant_type为authorization_code时 必选类型及范围说明 code truestring 调用authorize获得的code值。 redirect_uri truestring 回调地址,需需与注册应用里的回调地址一致。 */ NSURL *tokenurl = [NSURL URLWithString:@"https://api.weibo.com/oauth2/access_token"]; NSMutableURLRequest *tokenreq = [[NSMutableURLRequest alloc] initWithURL:tokenurl]; tokenreq.HTTPMethod = @"POST"; NSString *htpbody = [NSStringstringWithFormat:@"client_id=4293602466&client_secret=4a959234e47bb0fe313b986e610d2891&grant_type=authorization_code&code=%@&redirect_uri=http://www.baidu.com",code]; tokenreq.HTTPBody = [htpbody dataUsingEncoding:NSUTF8StringEncoding]; NSURLConnection *urc = [[NSURLConnection alloc] initWithRequest:tokenreq delegate:self]; [urc start]; } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@",response); } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSDictionary *jdic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSString *access_token = jdic[@"access_token"]; NSLog(@"%@",access_token); } @end
时间: 2024-10-13 11:26:38