從 iOS 9 起,系統預設啟用 App Transport Security(ATS),會攔下所有未加密的 HTTP 連線。若後端暫時無法全面升級,最快的解法是在 Info.plist 中關閉這道限制:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
要提醒的是,這等於關掉傳輸層的保護,只適合開發階段或過渡期使用;正式上線仍應把伺服器端導向 HTTPS,並改用 NSExceptionDomains 針對特定網域開例外,而非全域放行。
以下示範同步請求的基本骨架:
NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1/default.aspx?USER=%@", @"111"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"GET"];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSMutableString *result = [[NSMutableString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSLog(@"The result string is :%@", result);
注意:同步請求會阻塞主執行緒,正式環境請改用非同步方式(NSURLSession preferred)。
HTTPS 會多了「憑證驗證」這一層互動,因此需要用 delegate 處理認證挑戰:
NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1/default.aspx?USER=%@", @"111"];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:5];
// 設定請求方式為 GET
[request setHTTPMethod:@"GET"];
// 設定內容類型
[request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
// 送出請求
finished = false;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
// 阻塞等待結束
while (!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
各回呼方法的實作:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection {
return NO;
}
// 以下兩個方法是重點:伺服器端單向 HTTPS 驗證時,
// 由 iOS 客戶端自行決定是否接受憑證。
- (BOOL)connection:(NSURLConnection *)connection
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod
isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"didReceiveAuthenticationChallenge %@ %zd",
[[challenge protectionSpace] authenticationMethod],
(ssize_t)[challenge previousFailureCount]);
if ([[challenge protectionSpace] authenticationMethod]
isEqualToString:NSURLAuthenticationMethodServerTrust) {
[[challenge sender] useCredential:[NSURLCredential
credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
// 處理接收到的資料
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {}
實務建議:上述「無條件信任伺服器憑證」的寫法會讓中間人攻擊有機可乘,只可用於測試環境。正式環境應改用 NSURLSession 並搭配憑證比對(certificate pinning),才是安全的做法。