做網路相關功能時,把 HTTPS 請求的細節封裝成一個類別,往往能讓呼叫端清爽不少。以下分享一個我寫的 httpsClass,它會同步發送 POST 請求、處理伺服器憑證,並把回應結果以字串形式回傳。
#import <Foundation/Foundation.h>
@interface httpsClass : NSObject {
NSMutableURLRequest *_request;
NSURLConnection *connection;
NSStringEncoding enc;
NSURLAuthenticationChallenge *_challenge;
NSMutableData *muData;
bool isFinish;
}
- (NSString *)initWithUrl:(NSString *)url postData:(NSString *)data;
@end
初始化時設定 encoding、組出 POST 請求本文,建立連線後,用一個 RunLoop 迴圈「同步等待」直到回應完成:
- (NSString *)initWithUrl:(NSString *)requestUrl postData:(NSString *)data {
enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrl]];
NSData *aData = [data dataUsingEncoding:NSUTF8StringEncoding];
[_request setHTTPMethod:@"POST"];
[_request setHTTPBody:aData];
assert(_request != nil);
connection = [NSURLConnection connectionWithRequest:_request delegate:self];
if (connection) {
muData = [[NSMutableData data] retain];
}
isFinish = NO;
while (!isFinish) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]];
}
return [[NSString alloc] initWithData:muData encoding:NSUTF8StringEncoding];
}
因為走的是 HTTPS,需要在 didReceiveAuthenticationChallenge: 中信任伺服器憑證,才能完成連線:
- (BOOL)connection:(NSURLConnection *)conn
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)conn
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
_challenge = [challenge retain];
NSURLProtectionSpace *protectionSpace = [_challenge protectionSpace];
SecTrustRef trust = [protectionSpace serverTrust];
NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
[[_challenge sender] useCredential:credential forAuthenticationChallenge:_challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ((httpResponse.statusCode / 100) != 2) {
[self _stopReceiveWithStatus:[NSString stringWithFormat:@"HTTP error %zd", (ssize_t)httpResponse.statusCode]];
}
[muData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[muData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
isFinish = YES;
[self _stopReceiveWithStatus:nil];
}
httpsClass *http = [httpsClass new];
NSString *postPram = [NSString stringWithFormat:
@"requestData={\"api_Channel\":\"3\",\"api_name\":\"api.news.find_article_weekly_daily_news_list\",\"params\":{\"type\":%d,\"pageNo\":%d,\"pageSize\":%d}}",
1, 1, 10];
NSLog(@"%@", [http initWithUrl:@"https://**.**.**.**/api/x.htm" postData:postPram]);
執行後,就會把伺服器回傳的內容印出來。
需要特別提醒的是:這個類別用「在 RunLoop 上原地等待」的方式做同步請求,會阻塞呼叫它的執行緒;若在主執行緒呼叫,整個 UI 都會被卡住。因此在正式環境中,建議把它放到背景執行緒執行,或改用非同步的 NSURLSession 搭配 completion 回呼,才是更推薦的做法。此外,直接把伺服器憑證無條件信任(credentialForTrust)等於關閉了憑證驗證,僅適合測試或自用伺服器,正式環境仍應驗證憑證是否合法,以免中了中間人攻擊。