標籤:
/* X-Code7NSURLConnection已經被棄用了,官方建議使用NSURLSession(ios7之後就已經出現了),在NSURLConnection的基礎上進行的封裝 */#if 0 NSString * path = @"http://10.0.8.8/sns/my/user_list.php?number=10&page=2"; //如果有參數 在URL後面用?串連起來 參數 = 具體的資料 //多個參數 用&串連起來 //如果是直接在URL後面加上參數 這種事get請求 預設就是get請求 NSURL * url = [NSURL URLWithString:path]; //請求類對象 NSURLRequest * request = [NSURLRequest requestWithURL:url]; //NSURLSession對象 NSURLSession * session = [NSURLSession sharedSession]; //NSURLSession資料任務 網路連接 NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",obj); }else{ NSLog(@"%@",error); } }]; //啟動任務 啟動下載 [task resume];#else NSString * path = @"http://10.0.8.8/sns/my/user_list.php"; NSURL * url = [NSURL URLWithString:path]; NSMutableURLRequest * request = [[NSMutableURLRequest alloc]initWithURL:url]; //如果不設定 預設就是get //佈建要求的方式 request.HTTPMethod = @"POST"; //不能在URL後面直接拼它的參數 //需要把參數寫到請求的body裡 NSString * str = @"number=10&page=2"; //佈建要求的body request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding]; NSURLSession * session = [NSURLSession sharedSession]; NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",obj); }else{ NSLog(@"%@",error); } }]; [task resume]; #endif
NSURLSession的GET和POST下載