封装AFN的方法,默认不支持数组的表单请求
1.把数组从字典中拿出来
2.把数组内容转换为NSData添加到表单数据当中
+(void)postFormJava:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithDictionary:params];
NSMutableDictionary *mArrayDict = [NSMutableDictionary dictionaryWithCapacity:4];
for (NSString *key in params.allKeys) {
id value = mdict[key];
if ([value isKindOfClass:[NSArray class]]) {
[mArrayDict setObject:value forKey:key];
[mdict removeObjectForKey:key];
}
}
params = mdict;
// 1.获得请求管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//设置超时的秒数
mgr.requestSerializer.timeoutInterval = 30;
[mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (NSString *key in mArrayDict) {
NSArray *values = mArrayDict[key];
for (NSNumber *value in values) {
NSString *valString = [value stringValue];
NSData *data = [[NSData alloc] initWithBytes:[valString UTF8String] length:valString.length];
[formData appendPartWithFormData:data name:key];
}
}
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *dict;
if ([responseObject isKindOfClass:[NSDictionary class]])
{dict = [responseObject copy];
}
else{
dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
}
success(dict);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
请求框架字典转表单部分:
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(method);
NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
__block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
if (parameters) {
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
NSData *data = nil;
if ([pair.value isKindOfClass:[NSData class]]) {
data = pair.value;
} else if ([pair.value isEqual:[NSNull null]]) {
data = [NSData data];
} else {
data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
}
if (data) {
[formData appendPartWithFormData:data name:[pair.field description]];
}
}
}
if (block) {
block(formData);
}
return [formData requestByFinalizingMultipartFormData];
}