最近 POST 請求遇到一個問題:只要參數裡有中文,請求就會失敗。以下用兩種寫法對照說明差異。
// 1. 設定 URL
NSString *host = HOST;
NSString *userName = @"testUser";
NSString *queryString = [NSString stringWithFormat:
@"/app/clickTableScreen?userName=%@&idfa=%@&operator=%@&systemVersion=%@"
@"&networkState=%@&deviceName=%@&memorySize=%@&model=%@",
userName, adId, [self checkCarrier], phoneVersion, netStr,
userPhoneName, totalDiskSpaceStr, [LoginViewController deviceString]];
NSLog(@"queryString:%@", queryString);
NSString *urlString = [NSString stringWithFormat:@"%@%@", host, queryString];
NSLog(@"參數:%@", urlString);
NSURL *url1 = [NSURL URLWithString:url1 = urlString];
// 2. 建立 Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url1
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
[request setHTTPMethod:@"POST"];
// 3. 連接伺服器
NSError *error = nil;
NSData *reqData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
if (reqData == nil) {
if (error) {
// 這樣寫的好處:解析失敗時系統會印出明確原因。
// 我就是靠這行才看到:Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
NSLog(@"error = %@", error);
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"網路不穩定,請稍後嘗試!"
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:@"ok", nil];
[alert show];
return;
}
NSDictionary *reqDic = [NSJSONSerialization JSONObjectWithData:reqData
options:NSJSONReadingAllowFragments
error:nil];
NSString *info = [NSString stringWithFormat:@"%@", [reqDic objectForKey:@"info"]];
NSLog(@"參數字典:%@", reqDic);
// 4. 檢查回應
NSString *errcode = [NSString stringWithFormat:@"%@", [reqDic objectForKey:@"errcode"]];
if ([errcode isEqualToString:@"0"]) {
NSLog(@"成功了");
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"獲取廣告標識符失敗"
message:info
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
}
問題出在最後交給 NSURL 的那一步。URL 若含有中文或空白等非 ASCII 字元,URLWithString: 會回傳 nil,接著 request 就是一個 unsupported URL,錯誤碼 -1002。
其餘部分完全相同,只在中間多了一行:
NSString *urlString = [NSString stringWithFormat:@"%@%@", host, queryString];
NSLog(@"參數:%@", urlString);
// 有中文的時候必須先做百分比編碼
NSString *encoded = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encoded];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
[request setHTTPMethod:@"POST"];
NSError *error = nil;
NSData *reqData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
HTTP 的 URL 只允許 ASCII 字元中的一小子集,中文必須先轉成 UTF-8 位元組再做百分比編碼(percent-encoding),伺服器才認得。這一步不做,請求在建構階段就已經失敗,根本還沒離開裝置。
不過要提醒的是,stringByAddingPercentEscapesUsingEncoding: 有兩個明顯缺陷:它不會編碼 &、=、? 這些有語意的分隔字元(這是好事,因為它們是 URL 結構的一部分),但同時也不會處理 +、# 等容易出問題的字元。更嚴謹的做法是用 NSURLComponents 搭配 queryItems:
NSURLComponents *components = [NSURLComponents componentsWithString:host];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"userName" value:userName],
[NSURLQueryItem queryItemWithName:@"idfa" value:adId],
[NSURLQueryItem queryItemWithName:@"model" value:model]
];
NSURL *url = components.URL; // 編碼由系統負責,不會出錯
另外,既然參數中已經含有中文,其實更合適的做法是把這些參數放進 POST body,而不是塞在 query string 裡。URL 本來就該保持簡短且不含敏感資訊,把使用者名稱、裝置識別碼放進 body 並設定 Content-Type: application/x-www-form-urlencoded,才是更規範的設計。