#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, copy) NSString *username;//用户名
@property (nonatomic, copy) NSString *password;// 密码
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.username = @"zhangsan";
self.password = @"zhang";
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self postLogin];
}
/*
URL
GET: 需要在URL拼接参数
1.1 在URL后面先拼接一个问号
1.2 再拼接参数,参数是key=value 形式
1.3 多个参数之间,使用 & 来连接
POST:
2.1 不需要在URL在拼接参数
NSURLRequest
GET: 默认就是GET请求
POST: 需要使用可变的请求
3.1 设置HTTP的请求方法为POST
3.2 拼接参数,并且转成NSData设置给请求体HTTPBody
3.3 参数格式是key=value,多个参数之间使用 & 来拼接
NSURLConnection
没有任何的区别
*/
- (void)postLogin {
// 拼接POST参数
NSString *params = [NSString stringWithFormat:@"username=%@&password=%@",self.username,self.password];
// 在真实开发中,项目名或者文件夹尽量不要使用中文
NSString *URLString = [NSString stringWithFormat:@"http://localhost/login.php"];
// NSURL 在工作中,不止是php为后缀,还有可能是其他的,jsp,asp,.do,.action,不管什么后缀,在我们眼里都是一样的
NSURL *url = [NSURL URLWithString:URLString];
// NSURLRequest
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 请求默认是GET,如果要使用POST必须是可变的请求
// 设置POST请求
[request setHTTPMethod:@"POST"];
// 设置POST参数,不需要百分号转码
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
// NSURLConnection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@"%@",response);
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",result);
}];
}
- (void)getLogin {
// 拼接URLhttp://localhost/login.php?username=zhangsan&password=zhang
// 如果URL中出现中文或者是空格或者其他的特殊字符串,就必须转百分号编码
// 在真实开发中,项目名或者文件夹尽量不要使用中文
NSString *URLString = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@",self.username,self.password];
// 转码
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"%@",URLString);
// NSURL 在工作中,不止是php为后缀,还有可能是其他的,jsp,asp,.do,.action,不管什么后缀,在我们眼里都是一样的
NSURL *url = [NSURL URLWithString:URLString];
// NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// NSURLConnection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@"%@",response);
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"%@",result);
}];
}
@end
网路:POST 登录
最新推荐文章于 2024-03-21 07:30:00 发布