ios的post提交

来源:互联网 发布:网络交友的危害的例子 编辑:程序博客网 时间:2024/06/11 02:28

ios的post提交

 

C代码  收藏代码
  1. //post提交的参数,格式如下:  
  2.     //参数1名字=参数1数据&参数2名字=参数2数据&参数3名字=参数3数据&...  
  3.     NSString *post = [NSString stringWithFormat:@"m=check_user_login_info&f=itemgarden_iphone_app&u=%@&s=%@",self.us_email,self.us_password];  
  4.       
  5.     NSLog(@"post:%@",post);  
  6.       
  7.     //将NSSrring格式的参数转换格式为NSData,POST提交必须用NSData数据。  
  8.     NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];  
  9.     //计算POST提交数据的长度  
  10.     NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];  
  11.     NSLog(@"postLength=%@",postLength);  
  12.     //定义NSMutableURLRequest  
  13.     NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
  14.     //设置提交目的url  
  15.     [request setURL:[NSURL URLWithString:kUserLoginCheckUrl]];  
  16.     //设置提交方式为 POST  
  17.     [request setHTTPMethod:@"POST"];  
  18.     //设置http-header:Content-Type  
  19.     //这里设置为 application/x-www-form-urlencoded ,如果设置为其它的,比如text/html;charset=utf-8,或者 text/html 等,都会出错。不知道什么原因。  
  20.     [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
  21.     //设置http-header:Content-Length  
  22.     [request setValue:postLength forHTTPHeaderField:@"Content-Length"];  
  23.     //设置需要post提交的内容  
  24.     [request setHTTPBody:postData];  
  25.       
  26.     //定义  
  27.     NSHTTPURLResponse* urlResponse = nil;  
  28.     NSError *error = [[NSError alloc] init];  
  29.     //同步提交:POST提交并等待返回值(同步),返回值是NSData类型。  
  30.     NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
  31.     //将NSData类型的返回值转换成NSString类型  
  32.     NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];  
  33.     NSLog(@"user login check result:%@",result);  
  34.       
  35.     if ([@"success" compare:result]==NSOrderedSame) {  
  36.         return YES;  
  37.     }  
  38.     return NO;  
0 0