在发送网络请求时,不论是GET请求还是POST请求,请求的方法都是一样的,不同的是在发送请求过程中携带的请求不同,也就是NSURLRequest或其子类NSMutableURLRequest不同。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
//2.创建可变请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.修改请求方法,POST必须大写
request.HTTPMethod = @"POST";
//设置属性,请求超时
request.timeoutInterval = 10;
//设置请求头User-Agent
//注意:key一定要一致(用于传递数据给后台)上图中有请求头中包含的Key
[request setValue:@"ios 10.1" forHTTPHeaderField:@"User-Agent"];
//4.设置请求体信息,字符串--->NSData
request.HTTPBody = [@"username=520it&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
//5.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//6.解析数据,NSData --->NSString
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
}