本文以新浪微博的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 不然会报错。