首页 > 代码库 > AFNetworking2.0后 进行Post请求
AFNetworking2.0后 进行Post请求
本文以新浪微博的Oauth认证为例子进行Post请求的演示
下面直接上代码:
#import "ViewController.h" #import "AFNetworking.h" @interface ViewController ()<UIWebViewDelegate,NSURLConnectionDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString* urlStr = @"https://api.weibo.com/oauth2/authorize?client_id=3145625561&redirect_uri=http://www.baidu.com&display=mobile"; //将字符串转化为URL NSURL* url = [NSURL URLWithString:urlStr]; NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url]; UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame]; [webView loadRequest:request]; webView.delegate = self; [self.view addSubview:webView]; } - (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL* resultStr = [request URL]; NSString* tempStr = [resultStr absoluteString]; NSLog(@"%@",resultStr); //判断字符串中是否包含code= NSRange range = [tempStr rangeOfString:@"code="]; //如果不包含会返回为真,因此此处取反,就是说不为空的时候会为假,取反之后为真 if ( !(range.location == NSNotFound)) { //absoluteString作用是将NSURL类型转化为NSString NSString* tempStr = [resultStr absoluteString]; //componentsSeparatedByString NSArray* codeArr = [tempStr componentsSeparatedByString:@"="]; NSLog(@"%@",codeArr); NSString* code = [codeArr objectAtIndex:1]; NSLog(@"code = %@",code); //之后在此处下一行添加调用获取access_token值的方法即httpRequest:(NSString*)codeStr [self httpPostRequest:code]; } return YES; } - (void)httpPostRequest:(NSString *)code { /****本文主要讲解内容*****/ AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"]; NSDictionary *parameters = @{@"client_id":@"3145625561", @"client_secret":@"0a61cc8a017fa8ba6c98532fefa3c29c", @"grant_type":@"authorization_code", @"code":code, @"redirect_uri":@"http://www.baidu.com"}; [manager POST:@"https://api.weibo.com/oauth2/access_token?" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Success:%@" , responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@",error); }]; }
特别提示一下:
manager.responseSerializer.acceptableContentTypes = [NSSetsetWithObject:@"text/plain"];这里如果返回是JSON的话要用 text/plain 不然会报错。
代码例子:http://pan.baidu.com/s/1bn0FieN
AFNetworking2.0后 进行Post请求
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。