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