1、 AFNetworking 设置 timeout
在初始化 manager 时,可以设置
sharedInstance.requestSerializer.timeoutInterval = kRequestTimeOut;
2、AFNetworking 使用自签名证书
首先要拿到证书(.cer格式),一开始是从 keychain 里面获得的,但是这个证书一直不管用,后面替换成从 Windows 系统里面导出来的,就可以用了,原因未知。
然后对 AFHTTPSessionManager 做一些设置,主要就是替换原来的 securityPolicy,其它地方不用动,即可使用;
- (instancetype)init {
if (self = [super init]) {
_httpManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
// 发送数据时用 JSON 格式
_httpManager.requestSerializer = [AFJSONRequestSerializer serializer];
// 使用自签名证书时必须做下面这些设置
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"dbserver" ofType:@"cer"];
NSData * certData =[NSData dataWithContentsOfFile:cerPath];
NSSet * certSet = [[NSSet alloc] initWithObjects:certData, nil];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
// 是否允许,NO-- 不允许无效的证书
securityPolicy.allowInvalidCertificates = YES; // 必须设置为 YES
securityPolicy.validatesDomainName = NO; // 一定要设置为 NO
// 设置证书
[securityPolicy setPinnedCertificates:certSet];
// 替换默认的 securityPolicy
_httpManager.securityPolicy = securityPolicy;
}
return self;
}
截图
3、设置请求与接收的数据格式
AFNetworking中的 AFHTTPSessionManager 有两个属性,可以设置请求和接收的数据格式:
requestSerializer 请求序列化器,用于序列化请求参数
responseSerializer 响应序列化器,用于序列化返回的数据
每一种都有多个子类,用于不同的情况下
AFHTTPRequestSerializer:
AFJSONRequestSerializer
[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
AFPropertyListRequestSerializer
[mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
AFHTTPResponseSerializer:
AFJSONResponseSerializer
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
AFXMLParserResponseSerializer
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
AFXMLDocumentResponseSerializer
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
AFPropertyListResponseSerializer
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
AFImageResponseSerializer
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
在初始化 manager 的时候可以用上面的子类初始化一个对象,设置给 requestSerializer 和 responseSerializer