1. 创建网络请求工具类:
@interface CHHTTPTool : NSObject
2. CHHTTPTool.h文件:
GET请求方法声明:
/** * GET请求 * * @param URLString 请求地址 * @param parameters 请求参数 * @param success 成功回调 * @param failure 失败回调 */ + (void)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure;;
POST请求方法声明:
/** * POST请求 * * @param URLString 请求地址 * @param parameters 请求参数 * @param success 成功回调 * @param failure 失败回调 */ + (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure;
3. CHHTTPTool.m文件
GET请求方法实现:
+ (void)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure { // 请求管理者 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 发送请求 [manager GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) { success(responseObject); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) { failure(error); } }]; }
POST请求方法实现:
+ (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure { // 请求管理者 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 发送请求 [manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) { success(responseObject); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) { failure(error); } }]; }