在發送網絡請求時,不論是GET請求還是POST請求,請求的方法都是一樣的,不同的是在發送請求過程中攜帶的請求不同,也就是NSURLRequest或其子類NSMutableURLRequest不同。
請求頭、響應頭.png
-(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]);
}];
}