1、修改AFNetworking中修改源碼,在AFSecurityPolicy.m注釋掉這幾句
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
// if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == GMAFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
// // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
// // According to the docs, you should only trust your provided certs for evaluation.
// // Pinned certificates are added to the trust. Without pinned certificates,
// // there is nothing to evaluate against.
// //
// // From Apple Docs:
// // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
// // Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
// NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
// return NO;
// }
或者可以添加一個宏開關“openHttpsSSL”,便于控制,類似如下代碼
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
if (openHttpsSSL && domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
// According to the docs, you should only trust your provided certs for evaluation.
// Pinned certificates are added to the trust. Without pinned certificates,
// there is nothing to evaluate against.
//
// From Apple Docs:
// "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
// Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
return NO;
}
2、在使用的時候添加
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
// allowInvalidCertificates 是否允許無效證書(也就是自建的證書),默認為NO
// 如果是需要驗證自建證書,需要設置為YES
securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy = securityPolicy;
3、如果需要在http 頭里面添加用戶名和密碼驗證,添加
[request.operationManager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"用戶名" password:@"密碼"];