1. 程式人生 > >iOS開發-https免證書驗證

iOS開發-https免證書驗證

此處博主做一個宣告,如果你想跳過https的雙向驗證,僅僅單向進行直接信任所有的證書,那麼你們的後臺也必須是允許單向驗證的,否則設定了雙向驗證,客戶端是無法跳過的,實在不想當初辛苦的經驗被無知的小白說成無用的垃圾,謝謝。想知道雙向驗證怎麼做的,請在https分類中查詢對應方法。

前段時間博主做的專案中再登入時遇到了https驗證的問題,這裡跟iOS9之後要用https有區別,因為原來很多公司的介面都是http的,所以為了能讓http在iOS9上仍然能夠正常工作,可以在 plist手動設定來允許http訪問,我這裡介面本身為https,博主也是百度了很多資料在看,總的來說網上的關於https的資料並不多,而且還不正確。
一般來說https是需要雙向證書驗證的,也有單向的證書驗證,因為後臺偷懶,證書檔案沒有給我就造成了我這邊準備了好幾套https證書驗證的程式碼,卻不知道正確與否,所以現在我的https介面採用的是https免證書驗證,博主試了下抓介面也是抓不到資料的,在實現代理抓介面的情況下,這個介面不能成功調通,那麼下面我來貼下AFNetWorking使用https免證書驗證的程式碼,至於證書驗證因為博主沒驗證過也就不把程式碼貼出來坑人了,如果以後有機會接觸,會回來把部落格更新一下的,現在貼下https免驗證程式碼:

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSLog(@"%@",manager.requestSerializer.HTTPRequestHeaders);
policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    manager.responseSerializer=[AFJSONResponseSerializer serializer];
 //這裡是博主的訊息頭鑑權,並非所有的公司都會鑑權,所以不用在意下面這句話
[manager.requestSerializer setValue:[[[ZAApiRequest alloc]init] headerString:@"xxxxxxxxxxxxxxxxxxxxxxx"] forHTTPHeaderField:@"Authorization"]; AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; securityPolicy.allowInvalidCertificates
= YES; //還是必須設成YES NSString *URLTmp = @"https://xxxxxxxxxxxxxxxxxxxxx" URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //轉碼成UTF-8 否則可能會出現錯誤 [manager POST:URLTmp1 parameters:_updataDic success:^(AFHTTPRequestOperation *operation, id responseObject) { [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES]; //判斷是否登陸成功 NSDictionary *result=[responseObject objectForKey:@"result"]; NSString *resultCode=[result objectForKey:@"resultCode"]; if (![resultCode isEqual:@"00000000"]) { UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"賬號或密碼錯誤,請確認後重新輸入。" delegate:self cancelButtonTitle:@"確定" otherButtonTitles: nil]; [alertView show]; return ; } else { [MBProgressHUD showSuccess:@"登陸成功"]; } NSLog(@"%@",manager.requestSerializer.HTTPRequestHeaders); NSLog(@"%@",responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error:%@",error); }];

以上方法可以實現https免證書驗證。親測無誤。