POST請(qǐng)求和GET請(qǐng)求相像
0.首先得有一個(gè)NSURL,告訴請(qǐng)求路徑。此時(shí)POST請(qǐng)求的請(qǐng)求參數(shù)不是放請(qǐng)求路徑(放在請(qǐng)求體里)
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1.請(qǐng)求路徑
NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
//2.創(chuàng)建請(qǐng)求對(duì)象
NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
//告知是GET請(qǐng)求還是POST請(qǐng)求
//更改請(qǐng)求方法,不寫的話就是GET
requset.HTTPMethod = @"POST";
//設(shè)置請(qǐng)求體
requset.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
//設(shè)置超時(shí)(5秒后超時(shí))只有用NSMutableURLRequest才行
requset.timeoutInterval = 5;
//設(shè)置請(qǐng)求頭
// [requset setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
//3.發(fā)送請(qǐng)求
[NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {//比如請(qǐng)求超時(shí)
NSLog(@"----請(qǐng)求失敗");
}else{
NSLog(@"----%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
}
NSMutableURLRequest
》設(shè)置請(qǐng)求超時(shí)等待時(shí)間(超過這個(gè)時(shí)間,請(qǐng)求失?。?br> timeoutInterval/setTimeoutInterval
》設(shè)置請(qǐng)求體
HTTPBody/setHTTPBody
》設(shè)置請(qǐng)求頭
setValue:value forHTTPHeaderField:
創(chuàng)建GET和POST請(qǐng)求
創(chuàng)建GET請(qǐng)求
請(qǐng)求路徑 -> 轉(zhuǎn)成 url -> NSURLRequest
默認(rèn)就是GET請(qǐng)求
NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:...];
創(chuàng)建POST請(qǐng)求
url -> requset ->改成POST ->請(qǐng)求體
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:...];
兩者區(qū)別比較的大的地方就在請(qǐng)求參數(shù)