直接上代码:
示例:(在storyboard中拖两个控件textField、一个UIButton,连线(userNameText、password、login))
@interface ViewController()
@property(nonatomic,weak)IBOutlet UITextField *userNameText;
@property(nonatomic,weak)IBOutlet UITextField *passWord;
@end
-(IBAction)login
{
[self postLoginWithUserName:self.userNameText.text password:self.passWord.text];
}
post登陆
-(void)postLoginWithUserName:(NSString *)userName password:(NSString *)password
{
//1.url
NSURL *url = [NSURL URLWithString:@"http://本机IP/login.php"];
//2.request
NSMutableNSURLRequest *request = [NSMutableNSURLRequest requestWithURL:url];
//对于post请求的数据题要和request一起提交
request.HTTPMethod = @"POST";
//准备数据题
NSString *bodyString = [NSString *stringWithFormat:@"username=%@&password=%@",username,password];
//设置二进制数据
request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//3.发送网络连接,获取二进制数据
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLReponse *response,NSData *data,NSError *connectionError)];
NSString *result = [NSString alloc]initWithData:data encoding:NSUTF8Encoding];
}
get登陆
-(void)getLoginWithUserName:(NSString *)userName password:(NSString *)password
{
//1.url
NSString *urlString = [NSString stringWithFormat:@"http://本机IP地址/login.php?username = %@&password = %@",userName,password];
//百分号转义
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
//2.request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送网络连接,获取二进制数据
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLReponse *response,NSData *data,NSError *connectionError)];
NSString *result = [NSString alloc]initWithData:data encoding:NSUTF8Encoding];
}
小结:
1.
get:
http://本机IP地址/login.php?username = %@&password = %@
http://ip地址/登陆的脚本文件?(后面有参数)参数变量名 = 参数数值&(继续接参数)变量名 = 数值
post
http://ip地址/登陆的脚本
2.request
get:什么都不需要处理,因为参数已经在URL中指定了
post:指定访问方法
HTTPMethod = @"post";
指定二进制数据
HTTPBody = 参数字符串的二进制数据
3.NSURLConnection 异步
get和post一样
在实际网络开发中,真正会发生变化的地方就在请求