AFN 3.0 POST请求适配 iOS 7.0问题

一直使用的AFN,在iOS8.0和9.0都没有问题,就在iOS 7.0 的系统总是出现 404错误,缺少 Content-Lenght 请求头参数,查阅了一圈资料没有找到好的解决办法,只好自己来写,直接上代码

if ([UIDevice currentDevice].systemVersion.integerValue >= 8.0) {

session = [manager POST:url parameters:params constructingBodyWithBlock:nil progress:^(NSProgress * _Nonnull uploadProgress) {

if (progress) {

progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);

}

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

[self successResponse:responseObject callback:success];

if (sg_cachePost) {

[self cacheResponseObject:responseObject request:task.currentRequest  parameters:params];

}

[[self allTasks] removeObject:task];

if ([self isDebug]) {

[self logWithSuccessResponse:responseObject

url:absolute

params:params];

}

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

[[self allTasks] removeObject:task];

[self handleCallbackWithError:error fail:fail];

if ([self isDebug]) {

[self logWithFailError:error url:absolute params:params];

}

}];

}else{

NSURL *url = [NSURL URLWithString:absolute];

NSMutableString *bodyContent = [NSMutableString string];

NSDictionary *dicData = [self addPublicParamsWithDic:params];

for(NSString *key in dicData.allKeys){

id value = [dicData objectForKey:key];

[bodyContent appendFormat:@"--%@\r\n",POST_BOUNDS];

[bodyContent appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];

[bodyContent appendFormat:@"%@\r\n",value];

}

[bodyContent appendFormat:@"--%@--\r\n",POST_BOUNDS];

NSData *bodyData=[bodyContent dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];

[request addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",POST_BOUNDS] forHTTPHeaderField:@"Content-Type"];

[request addValue: [NSString stringWithFormat:@"%zd",bodyData.length] forHTTPHeaderField:@"Content-Length"];

[request setHTTPMethod:@"POST"];

[request setHTTPBody:bodyData];

__autoreleasing NSError *error=nil;

__autoreleasing NSURLResponse *response=nil;

NSData *reciveData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if(error){

debug(@"出现异常%@",error);

[self handleCallbackWithError:error fail:fail];

}else{

NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;

if(httpResponse.statusCode==200){

[self successResponse:reciveData callback:success];

}else{

}

}

}

你可能感兴趣的:(AFN 3.0 POST请求适配 iOS 7.0问题)