博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

httpHelper请求辅助类

Posted on 2016-07-28 05:53  吕霖  阅读(378)  评论(0编辑  收藏  举报

#import <Foundation/Foundation.h>

#import "AFNetworking.h"

 

@interface AFHttpClient : NSObject

 

DEFINE_SINGLETON_FOR_HEADER(AFHttpClient);

 

/**

 *  判断网络是否正常

 *

 *  @return Bool YES 表示正常

 */

- (BOOL)isOnline;

/**

 *  停止请求

 */

- (void)cancelAllRequest;

/**

 *  Get 请求

 *

 *  @param path       路径

 *  @param parameters 参数

 *  @param success    success block

 *  @param failure    failure block

 */

- (AFHTTPRequestOperation *)getHttpRequest:(NSString *)path

             parameter:(NSDictionary *)parameters

               success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

               failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**

 *  Get 请求

 *

 *  @param url        路径

 *  @param parameter  参数

 *  @param completion completion block

 */

- (AFHTTPRequestOperation *)getHttpRequest:(NSString *)path

              paramter:(NSDictionary *)parameters

            completion:(void (^)(BOOL success))completion;

/**

 *  Post 请求

 *

 *  @param path       路径

 *  @param parameters 参数

 *  @param success    success block

 *  @param failure    failure block

 */

- (AFHTTPRequestOperation*)postHttpRequest:(NSString *)path

              parameter:(NSDictionary *)parameters

                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

 

/**

 *  Post 请求 发送json数据到服务端

 *

 *  @param path            路径

 *  @param parameters      参数

 *  @param success         success description

 *  @param postHttpRequest postHttpRequest description

 *  @param path            path description

 *  @param parameters      parameters description

 *  @param completion      completion description

 */

- (AFHTTPRequestOperation*)postJsonHttpRequest:(NSString *)path

                  parameter:(NSDictionary *)parameters

                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**

 *  Post 请求

 *

 *  @param url        路径

 *  @param parameter  参数

 *  @param completion completion block

 */

- (AFHTTPRequestOperation*)postHttpRequest:(NSString *)path

               paramter:(NSDictionary *)parameters

             completion:(void (^)(BOOL success))completion;

/**

 *  上传图片

 *

 *  @param uploadPath 上传路径

 *  @param imagePath  文件路径

 *  @param parameters 参数

 *  @param success    success block

 *  @param failure    failure block

 */

- (AFHTTPRequestOperation *)uploadImage:(NSString *)uploadPath

          imagePath:(NSString *)imagePath

          parameter:(NSDictionary *)parameters

            success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

            failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**

 *  上传图片

 *

 *  @param url        上传路径

 *  @param path       文件本地路径

 *  @param name       文件名

 *  @param parameter  参数

 *  @param completion block

 */

- (AFHTTPRequestOperation *)uploadImage:(NSString *)url

               path:(NSString *)path

               name:(NSString *)name

           paramter:(NSDictionary *)parameter

         completion:(void (^)(BOOL success))completion;

/**

 *  上传图片

 *

 *  @param url       上传路径

 *  @param imageData 图像数据

 *  @param imageName 图像名称

 *  @param fileName  文件名

 *  @param parameter 参数

 *  @param success   success block

 *  @param failure   failure block

 */

- (AFHTTPRequestOperation *)uploadImage:(NSString *)url

          imageData:(NSData *)imageData

          imageName:(NSString *)imageName

           fileName:(NSString*)fileName

           paramter:(NSDictionary *)parameter

            success:(void (^)(AFHTTPRequestOperation *operation,id responseObject))success

            failure:(void (^)(AFHTTPRequestOperation *operation,NSError *error))failure;

/**

 *  下载图片保存文件

 *

 *  @param url   地址

 *  @param path  文件名

 *  @param block block

 */

- (AFHTTPRequestOperation *)downloadImage:(NSString*)url

           saveToFile:(NSString *)path

           completion:(void (^)(bool success))block;

@end

 

.m文件

#import "AFHttpClient.h"

#import "AFNetworking.h"

#import "YQZTools.h"

#import "YQZSetting.h"

#import "Reachability.h"

#import "YQZViewController.h"

@interface AFHttpClient()

 

@property (nonatomic, strong) AFHTTPRequestOperationManager *currentRequest;

 

@end

 

@implementation AFHttpClient

 

DEFINE_SINGLETON_FOR_CLASS(AFHttpClient);

 

- (AFHTTPRequestOperationManager *)currentRequest

{

    if (!_currentRequest) {

        self.currentRequest = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:[YQZTools getProxy]]];

    }

    return _currentRequest;

}

 

- (BOOL)isOnline

{

    return [[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable;

}

 

#pragma mark - 请求 -

 

- (void)cancelAllRequest

{

    [self.currentRequest.operationQueue cancelAllOperations];

}

 

- (AFHTTPRequestOperation *)getHttpRequest:(NSString *)path

             parameter:(NSDictionary *)parameters

               success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

               failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{

    if(NotReachable == [[Reachability reachabilityForInternetConnection] currentReachabilityStatus]){

        if (![[YQZSetting sharedInstance] getAlertViewShow]) {

            [YQZTools alert:@"提示" message:@"您的网络不给力哦"];

            failure(nil,nil);

        }

        return nil;

    }

    

    [self showRequestLogWithUrl:path parameter:parameters];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    

    return [manager GET:path

      parameters:parameters

         success:^(AFHTTPRequestOperation *operation, id responseObject) {

             [self showSuccessLog:responseObject];

             

             int code = [[responseObject objectForKey:@"resultCode"] intValue];

             if (code == 399)      //系统错误

             {

                 failure(operation, nil);

                 return;

             }

             

             if (success)

             {

                 success(operation, responseObject);

             }

    }

         failure:^(AFHTTPRequestOperation *operation, NSError *error) {

             [self showErrorLog:error];

             if (failure) {

                 failure(operation, error);

             }

    }];

}

 

- (AFHTTPRequestOperation *)getHttpRequest:(NSString *)path

              paramter:(NSDictionary *)parameters

            completion:(void (^)(BOOL success))completion

{

    [self showRequestLogWithUrl:path parameter:parameters];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    return [manager GET:path

      parameters:parameters

         success:^(AFHTTPRequestOperation *operation, id responseObject) {

             [self showSuccessLog:responseObject];

             completion(YES);

    }

         failure:^(AFHTTPRequestOperation *operation, NSError *error) {

             [self showErrorLog:error];

             completion(NO);

    }];

}

 

 

- (AFHTTPRequestOperation*)postHttpRequest:(NSString *)path

              parameter:(NSDictionary *)parameters

                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{

    if(NotReachable == [[Reachability reachabilityForInternetConnection] currentReachabilityStatus]){

        if (![[YQZSetting sharedInstance] getAlertViewShow]) {

            [YQZTools alert:@"提示" message:@"您的网络不给力哦"];

            if (failure) {

                failure(nil,nil);

            }

        }

        return nil;

    }

    

    [self showRequestLogWithUrl:path parameter:parameters];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

 

    return [manager POST:path

       parameters:parameters

          success:^(AFHTTPRequestOperation *operation, id responseObject) {

              [self showSuccessLog:responseObject];

              

              int code = [[responseObject objectForKey:@"resultCode"] intValue];

              if (code == 399)      //系统错误

              {

                  failure(operation, nil);

                  return;

              }

              if (success)

              {

                  success(operation, responseObject);

              }

    }

          failure:^(AFHTTPRequestOperation *operation, NSError *error) {

              [self showErrorLog:error];

              failure(operation, error);

              

    }];

}

 

- (AFHTTPRequestOperation*)postJsonHttpRequest:(NSString *)path

                  parameter:(NSDictionary *)parameters

                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{

    if(NotReachable == [[Reachability reachabilityForInternetConnection] currentReachabilityStatus]){

        if (![[YQZSetting sharedInstance] getAlertViewShow]) {

            [YQZTools alert:@"提示" message:@"您的网络不给力哦"];

            failure(nil,nil);

        }

        return nil;

    }

    

    [self showRequestLogWithUrl:path parameter:parameters];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    //申明请求的数据是json类型

    manager.requestSerializer=[AFJSONRequestSerializer serializer];

    

    return [manager POST:path

       parameters:parameters

          success:^(AFHTTPRequestOperation *operation, id responseObject) {

              [self showSuccessLog:responseObject];

              

              int code = [[responseObject objectForKey:@"resultCode"] intValue];

              if (code == 399)      //系统错误

              {

                  failure(operation, nil);

                  return;

              }

              if (success)

              {

                  success(operation, responseObject);

              }

          }

          failure:^(AFHTTPRequestOperation *operation, NSError *error) {

              [self showErrorLog:error];

              failure(operation, error);

              

          }];

}

 

- (AFHTTPRequestOperation*)postHttpRequest:(NSString *)path

               paramter:(NSDictionary *)parameters

             completion:(void (^)(BOOL success))completion

{

    [self showRequestLogWithUrl:path parameter:parameters];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    return [manager POST:path

       parameters:parameters

          success:^(AFHTTPRequestOperation *operation, id responseObject) {

              [self showSuccessLog:responseObject];

              NSLog(@"responseObject: %@", responseObject);

              completion(YES);

    }

          failure:^(AFHTTPRequestOperation *operation, NSError *error) {

              [self showErrorLog:error];

              completion(NO);

    }];

}

 

#pragma mark - 上传下载 -

 

- (AFHTTPRequestOperation *)uploadImage:(NSString *)uploadPath

          imagePath:(NSString *)imagePath

          parameter:(NSDictionary *)parameters

            success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

            failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSURL *filePath = [NSURL fileURLWithPath:imagePath];

    return [manager POST:uploadPath parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileURL:filePath name:@"image" error:nil];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"Success: %@", responseObject);

        success(operation, responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"Error: %@", error);

        failure(operation, error);

    }];

}

 

- (AFHTTPRequestOperation *)uploadImage:(NSString *)url

               path:(NSString *)path

               name:(NSString *)name

           paramter:(NSDictionary *)parameter

         completion:(void (^)(BOOL success))completion

{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    return [manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:name error:nil];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"Upload Success: %@", responseObject);

        completion(YES);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"Upload Error: %@", error);

        completion(NO);

    }];

}

 

- (AFHTTPRequestOperation *)uploadImage:(NSString *)url

          imageData:(NSData *)imageData

          imageName:(NSString *)imageName

           fileName:(NSString*)fileName

           paramter:(NSDictionary *)parameter

            success:(void (^)(AFHTTPRequestOperation *operation,id responseObject))success

            failure:(void (^)(AFHTTPRequestOperation *operation,NSError *error))failure

{

    

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    return [manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData:imageData

                                    name:imageName

                                fileName:fileName

                                mimeType:@"image/*"];

    

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [self showSuccessLog:responseObject];

        NSLog(@"Upload Success: %@", responseObject);

        success(operation,responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"Upload Error: %@", error);

        failure(operation, error);

    }];

}

 

 

- (AFHTTPRequestOperation *)downloadImage:(NSString*)url

           saveToFile:(NSString *)path

           completion:(void (^)(bool success))block

{

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

 

        block(YES);

        NSLog(@"Successfully downloaded file to %@", path);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"%@", error);

        block(NO);

    }];

    

    [operation start];

    return operation;

}

 

#pragma mark - 日志 -

 

- (void)showRequestLogWithUrl:(NSString *)path parameter:(NSDictionary *)parameters

{

    NSLog(@"========请求路径==========================");

    NSLog(@"Request URL: \n%@ \nParameter:\n%@", path, parameters);

}

 

- (void)showSuccessLog:(id)responseObject

{

    NSLog(@"========✔️✔️✔️✔️========================");

    NSLog(@"请求成功!返回结果:\n%@", responseObject);

    NSLog(@"=========================================");

}

 

- (void)showErrorLog:(NSError *)error

{

    NSLog(@"========❌❌❌❌========================");

    NSLog(@"请求失败!错误描述:\n%@", error.localizedDescription);

    NSLog(@"=========================================");

}

 

@end