您的位置:首页 > 理论基础 > 计算机网络

iOS http访问post 、get

2015-12-28 23:48 441 查看
@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"];
//[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//[request setValue:@"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 *)aConn didReceiveData:(NSData *)data
{
//将接收的数据进行添加
[receivedData appendData:data];
}

// 网络错误时触发
- (void)connection:(NSURLConnection *)aConn didFailWithError:(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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: