GET 把參數拼在網址後面,POST 則是把參數放進 request 的 HTTPBody。差別不只是位置:POST 沒有長度限制、不會出現在伺服器日誌的網址列中,適合傳送較長或較敏感的資料。實作上,POST 必須用「可變的」NSMutableURLRequest,因為要事後設定 method 與 body。
- (IBAction)POSTSynButtonDidClicked:(UIButton *)sender {
NSString *baseUrlString = @"https://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:baseUrlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 1. 指定請求方法為 POST(預設是 GET)
[request setHTTPMethod:@"POST"];
// 2. 準備參數並轉成 NSData
NSString *bodyString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
// 3. 送出請求
NSData *receiveData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receiveData
options:NSJSONReadingMutableContainers error:nil];
NSArray *array = dict[@"news"];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in array) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
}
- (IBAction)POSTAsynButtonDidClicked:(UIButton *)sender {
NSString *baseUrlString = @"https://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:baseUrlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *bodyString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
[request setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers error:nil];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in dict[@"news"]) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
// 記得 reloadData,否則第一次畫面不會有內容
[self.tableView reloadData];
}];
}
一、Content-Type 要自己設。上面用的是 application/x-www-form-urlencoded 格式的字串,若伺服器要求 JSON body,必須補上這一行:
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
少了它,伺服器很可能解析不出參數而回傳 400。
二、中文參數要先編碼。body 字串裡若含中文或 &、= 等特殊字元,一樣得先做 URL encode,否則參數會被切錯。
三、異步回呼中更新 UI 要謹慎。若 queue 傳的不是 mainQueue,任何 UIKit 操作都必須 dispatch 回主執行緒。
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
同樣提醒:NSURLConnection 已在 iOS 9 廢棄,NSURLSession 才是現在的標準做法,寫法如下。
NSURLSessionDataTask *task = [[NSURLSession sharedSession]
dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// 解析 data
}];
[task resume];