AFNetwork学习(二)——GET/POST请求
为了学习AFNetwork,自己搭建整理了一下AFNetwork向后台发送请求和后台返回json数据的整个处理过程。利用Struts2搭建了一个后台,提供Action并返回json数据
环境:Xcode6.3
后台:tomcat+myeclipse10.6 框架:struts2
1.新建一个single-view applicationproject名为IOS_AFNetwork,开发语言选择OC.
2.将AFNetwork库文件增加到project中,例如以下图:
3.引入SystemConfiguration.framework、MobileCoreService.framework、Security.framework 。例如以下图:
4.在main.storyboard中加入两个button。发别用来发送get和post请求,并设置相应的响应函数。
例如以下图:
5.发送Get请求
//get请求 - (IBAction)getRuquest:(id)sender { //为了測试方便。自己搭建了一个javaweb后台 NSString *URLString = @"http://localhost:8080/server/login.action"; //传递參数 NSDictionary *loginInputValue = @{@"username" : @"1234567890", @"password" : @"123456"}; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer.timeoutInterval = self.timeInternal; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; self.operation = [manager GET:URLString parameters:loginInputValue success:^(AFHTTPRequestOperation *operation, id responseObject) { //解析后台返回的json串。将json转为字典 NSDictionary *responseData = [NSDictionary dictionaryFromJSONData:(NSData *)responseObject]; NSLog(@"success:%@",responseData); NSString *name = [responseData objectForKey:@"name"]; NSLog(@"name : %@",name); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error info :%@",[error description]); }]; }
6.发送Post请求
- (IBAction)postRequest:(id)sender { NSString *URLString = @"http://localhost:8080/server/login.action"; NSDictionary *loginInputValue = @{@"username" : @"1234567890", @"password" : @"123456"}; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer.timeoutInterval = self.timeInternal; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; self.operation = [manager POST:URLString parameters:loginInputValue success:^(AFHTTPRequestOperation *operation, id responseObject) { NSDictionary *responseData = [NSDictionary dictionaryFromJSONData:(NSData *)responseObject]; NSString *name = [responseData objectForKey:@"name"]; NSLog(@"name : %@",name); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error info :%@",[error description]); }]; }
OC代码下载地址:
http://download.csdn.net/detail/yuj9006/8876937
后台代码下载地址:
http://download.csdn.net/detail/yuj9006/8876999