AFNetworking的特殊设置
项目中的网络请求需要在Header
中添加Authorization
,并进行base64编码后请求数据。
设置
SecurityPolicy
有两种情况需要设置
SecurityPollicy
:- 使用HTTP请求,则需要在
plist
文件中设置允许HTTP请求,并添加host地址
到白名单,但有时请求仍会被Cancel(-999错误); - HTTPS请求,但是证书过期或无效了,请求可能被cancel
设置SecurityPolicy:
1
2
3
4
5
6AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
securityPolicy.validatesDomainName = NO;
securityPolicy.allowInvalidCertificates = YES;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;- 使用HTTP请求,则需要在
设置
base64
编码过的Authorization
在get请求时,可以使用
AFHTTPSessionManager
;但在post请求中AFHTTPSessionManager
无法满足需要,需要使用AFURLSessionManager
,并自定义Request来实现。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23//Authorization数据
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:@"IOS" forKey:@"os_type"];
if (login) {
if (![DDUser checkLogin]) {
return;
}
[dic setValue:[DDUser mainUser].token forKey:@"token"];
[dic setValue:[DDUser mainUser].userId forKey:@"userId"];
}else{
if ([DDUser checkLogin]) {
[dic setValue:[DDUser mainUser].token forKey:@"token"];
[dic setValue:[DDUser mainUser].userId forKey:@"userId"];
}
}
//base64编码
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
NSString *str = [jsonData base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:str forHTTPHeaderField:@"Authorization"];url编码
1
NSString *getURL = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
post
请求的参数需要转成json
时,需要使用AFURLSessionManager
而不是AFHTTPSessionManager
,需要自己来设置request
的header
和body
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28//post参数需要转成json时使用AFURLSessionManager
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.securityPolicy = securityPolicy;
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:postURL parameters:nil error:nil];
request.timeoutInterval= 60;
[request setValue:str forHTTPHeaderField:@"Authorization"];
[request addValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
if (parameters != nil) {
NSError *xxError;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&xxError]];
}
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
[self dismissHUD];
if (!error) {
if (successBlock) {
successBlock(responseObject);
}
}else{
if (failureBlock) {
failureBlock(error);
}
}
}] resume];设置response数据格式
1
2
3
4//get请求
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];post方法上传图片(拼接formData),需要注意的是post的数据参数名需要跟服务端要求的参数名保持一致:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57//securityPolicy
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
securityPolicy.validatesDomainName = NO;
securityPolicy.allowInvalidCertificates = YES;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
//url编码
NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//header数据
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:@"IOS" forKey:@"os_type"];
if (login) {
if (![DDUser checkLogin]) {
return;
}
[dic setValue:[DDUser mainUser].token forKey:@"token"];
[dic setValue:[DDUser mainUser].userId forKey:@"userId"];
}else{
if ([DDUser checkLogin]) {
[dic setValue:[DDUser mainUser].token forKey:@"token"];
[dic setValue:[DDUser mainUser].userId forKey:@"userId"];
}
}
//base64编码
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
NSString *str = [jsonData base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
//设置请求头
[manager.requestSerializer setValue:str forHTTPHeaderField:@"Authorization"];
[manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer.timeoutInterval = 60;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
[manager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSString *key = dataDic.allKeys.firstObject;
NSData *data = dataDic[key];
NSString *file = [NSString stringWithFormat:@"%@.jpeg",key];
//注意这里的参数名跟服务端要求的参数名称保持一致
[formData appendPartWithFileData:data name:@"editormd-image-file"//参数名
fileName:file mimeType:@"image/jpeg"];
}
progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (successBlock) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
successBlock(dict);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self dismissHUD];
if (failureBlock) {
failureBlock(error);
}
}];使用原生post请求(需要设置base64编码过的
Authorization
,需要url编码
,设置HTTPHeader):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53//Header数据
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:@"IOS" forKey:@"os_type"];
if (login) {
if (![DDUser checkLogin]) {
return;
}
[dic setValue:[DDUser mainUser].token forKey:@"token"];
[dic setValue:[DDUser mainUser].userId forKey:@"userId"];
}else{
if ([DDUser checkLogin]) {
[dic setValue:[DDUser mainUser].token forKey:@"token"];
[dic setValue:[DDUser mainUser].userId forKey:@"userId"];
}
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
//base64编码
NSString *str = [jsonData base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:str forHTTPHeaderField:@"Authorization"];
[request addValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
request.HTTPMethod = @"POST";
if (parameters != nil) {
NSError *xxError;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&xxError]];
}
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
if (successBlock) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
successBlock(dic);
}
}else{
if (failureBlock) {
failureBlock(error);
NSLog(@"请求发生错误error--->%@", error);
}
}
}];
[dataTask resume];