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 = [NSSet setWithObject:@"text/plain"];这里如果返回是JSON的话要用 text/plain 不然会报错。
代码例子:http://pan.baidu.com/s/1bn0FieN
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。