AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",[[NSUserDefaults standardUserDefaults] objectForKey:TOKEN]] forHTTPHeaderField:@"Authorization"]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [manager POST:@"http:xxxxx" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileData:profileImage name:@"file" fileName:@"profileImage.jpg" mimeType:@"image/jpeg"]; } success:^(NSURLSessionTask *task,id responSEObject) { completionHandler(responSEObject); } failure:^(NSURLSessionTask *operation,NSError *error) { NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]; NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil]; errorHandler(serializedData); }];
此方法工作正常,但不推荐使用constructBodyWithBlock.如何优化代码以符合AFNetworking 3.0标准?
解决方法
使用
POST:parameters:constructingBodyWithBlock:progress:success:failure:
再现(如果您不需要,则提供nil以获得进度).
您不需要设置Accept和Content-Type标头类型.它们分别由AFJSONResponseSerializer和AFJSONRequestSerializer设置.