#import
#import "AFNetworking.h"
typedef void(^DidFinishBlock)(AFHTTPRequestOperation *operation,id result);
typedef void(^DidFailBlock)(AFHTTPRequestOperation *operation,NSError *error);
@interface DataService : NSObject
//声明类方法
+ (AFHTTPRequestOperation *)requestWithURL:(NSString *)url
params:(NSMutableDictionary *)params
httpMethod:(NSString *)httpMethod
didFinishBlock:(DidFinishBlock)didFinishBlock
didFailBlock:(DidFailBlock)didFailBlock;
-------------------------------------------------------------------------------------------------------------------------
//类方法实现
@implementation DataService
+ (AFHTTPRequestOperation *)requestWithURL:(NSString *)url
params:(NSMutableDictionary *)params
httpMethod:(NSString *)httpMethod
didFinishBlock:(DidFinishBlock)didFinishBlock
didFailBlock:(DidFailBlock)didFailBlock{
//创建请求管理对象
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
AFHTTPRequestOperation *operation = nil;
if ([httpMethod isEqualToString:@"GET"]) {
operation = [manager GET:url
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功
// NSLog(@"AF-GET(无文件)请求成功");
if (didFinishBlock) {
didFinishBlock(operation,responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
// NSLog(@"AF-POST(无文件)请求失败");
if (didFailBlock) {
didFailBlock(operation,error);
}
}];
}else if([httpMethod isEqualToString:@"POST"]){
BOOL isFile = NO;
for (NSString *key in params) {
id value = params[key];
if ([value isKindOfClass:[NSData class]]) {
//有文件类型的参数
isFile = YES;
break;
}
}
if (!isFile) {
//不带文件
operation = [manager POST:url
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功
// NSLog(@"AF-POST(非文件)请求成功");
if (didFinishBlock) {
didFinishBlock(operation, responseObject);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
// NSLog(@"AF-POST(非文件)请求失败");
if (didFailBlock) {
didFailBlock(operation, error);
}
}];
}else{
//带文件
operation = [manager POST:url
parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (NSString *key in params) {
id value = params[key];
if ([value isKindOfClass:[NSData class]]) {
//往Form表单中添加data数据
[formData appendPartWithFileData:value
name:key
fileName:key
mimeType:@"p_w_picpath/jpeg"];
}
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功
// NSLog(@"AF-POST(带文件)请求成功");
if (didFinishBlock) {
didFinishBlock(operation,responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
// NSLog(@"AF-POST(带文件)请求失败");
if (didFailBlock) {
didFailBlock(operation,error);
}
}];
}
}
//设置返回数据的解析方式
operation.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];
return operation;
}