iphone之http post数据

来源:互联网 发布:周杰伦secret知乎 编辑:程序博客网 时间:2024/06/09 23:51

iphone之http post数据



在头文件中加入该语句:


@interface CoursePJViewController :BaseViewController<UITextViewDelegate,NetAccessDelegate,NSURLConnectionDataDelegate>




代码如下;

@synthesize nameFiled;//手机号

@synthesize passFiled;//密码

//登录时的按钮事件

- (IBAction)login

{

//post数据的手机号及密码

NSString *post =[NSString stringWithFormat:@"mobile=%@&password=%@",nameFiled.text,passFiled.text];

//将post数据转换为 NSASCIIStringEncoding 编码格式

   NSData *postData =[post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  

  

 

   NSMutableURLRequest *request= [[[NSMutableURLRequest alloc] init] autorelease];  

//要post的联通网址

   [request setURL:[NSURL URLWithString:@"http://client.10010.com/client/login.do"]];

//post类型

   [request setHTTPMethod:@"POST"];  

   //[requestsetValue:postLengthforHTTPHeaderField:@"Content-Length"];  

   //[requestsetValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];

 

//设置post数据

   [request setHTTPBody:postData]; 

 

//创建链接

NSURLConnection *conn =[[NSURLConnection alloc] initWithRequest:request delegate:self];

if (conn)   

    {  

if (receivedData != nil){

[receivedData release];

}

//创建数据接收域 

receivedData = [[NSMutableData alloc] initWithData:nil];

    } 

[conn release];

 

 

}

 

#pragma mark -

#pragma mark Http post 数据

// 每收到一次数据, 会调用一次

- (void)connection:(NSURLConnection *)aConndidReceiveData:(NSData *)data

{

//将接收的数据进行添加

[receivedData appendData:data];

}

// 网络错误时触发

- (void)connection:(NSURLConnection *)aConndidFailWithError:(NSError *)error

{

//错误的提示

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:[NSMutableString stringWithFormat:@"%@",error] delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];

[alert show];

[alert release];

}

// 全部数据接收完毕时触发

- (void)connectionDidFinishLoading:(NSURLConnection *)aConn

{

//将data 转换成为字符串

NSString *results= [[NSString alloc] 

                     initWithBytes:[receivedData bytes] 

                     length:[receivedData length] 

                     encoding:NSUTF8StringEncoding];

 

//接收的数据

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:results delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];

[alert show];

[alert release];

 

 

[results release];

}


原创粉丝点击