從 iOS 9 開始,App Transport Security(ATS)默認生效,所有明文 HTTP 請求都會被系統直接攔截。對於有大量歷史介面仍是 HTTP 的項目,這是一個必須正面處理的升級問題。
如果暫時無法把後端全部遷移到 HTTPS,可以在 Info.plist 中加入以下配置關閉 ATS 檢查:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
需要明確的是,這相當於全局關閉了傳輸安全保護,僅適合過渡期使用。上線前應盡量把介面遷移到 HTTPS,或者改用針對特定域名的白名單配置(NSExceptionDomains),把風險控制在最小範圍。
在具體代碼層面,兩者的請求構造幾乎一致,關鍵差異在於 HTTPS 需要處理證書信任的問題。
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);
注意 returningResponse: 需要傳遞地址 &urlResponse,原樣寫成變量名是無法拿到響應對象的。
當服務端採用單向 HTTPS 驗證、而 iOS 客戶端需要跳過證書信任檢查時,實現如下:
{
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"];
// 添加 Content-Type 頭
[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
{
finished = true;
[connection release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
finished = true;
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return NO;
}
// 以下兩個方法是重點:讓 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
{
}
finished 設為 YES,阻塞等待的 while 循環永遠不會退出,主線程會被卡死。sendSynchronousRequest: 會阻塞當前線程,放在主線程會直接凍結界面。