POST请求和GET请求相像
0.首先得有一个NSURL,告诉请求路径。此时POST请求的请求参数不是放请求路径(放在请求体里)
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1.请求路径
NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
//2.创建请求对象
NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
//告知是GET请求还是POST请求
//更改请求方法,不写的话就是GET
requset.HTTPMethod = @"POST";
//设置请求体
requset.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
//设置超时(5秒后超时)只有用NSMutableURLRequest才行
requset.timeoutInterval = 5;
//设置请求头
// [requset setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
//3.发送请求
[NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {//比如请求超时
NSLog(@"----请求失败");
}else{
NSLog(@"----%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
}
NSMutableURLRequest
》设置请求超时等待时间(超过这个时间,请求失败)
timeoutInterval/setTimeoutInterval
》设置请求体
HTTPBody/setHTTPBody
》设置请求头
setValue:value forHTTPHeaderField:
创建GET和POST请求
创建GET请求
请求路径 -> 转成 url -> NSURLRequest
默认就是GET请求
NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:...];
创建POST请求
url -> requset ->改成POST ->请求体
NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
requset.HTTPMethod = @"POST";
requset.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:...];
两者区别比较的大的地方就在请求参数
网友评论