iOS 网络请求封装类

    此类名为CWSingleSample,只为方便自己修改, 添加方法所记录!

  CWSingleSample.h

//
//  CWSingleSample.h
//  students
//
//  Created by ZKSoft on 14/11/13.
//  Copyright (c) 2014年 ZK. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "MBProgressHUD.h"
#import "AFHTTPRequestOperation.h"
#import "ASIHTTPRequest.h"
//请求成功时的回调block
typedef void (^getDataBlock)(id data);
//请求失败时的回调block
typedef void (^getErrorBlock)(NSError* error);
//上传文件时的回调block
typedef void (^getFileBlock)(NSString* fileName,id data);
//接口枚举
typedef enum {
   CWSMSSEND=0,//短信验证码发送
   CWUSERREGISTER,//用户注册
   CWUSERLOGIN,//用户登录
  CWPASSWORDDEAL,//密码修改/找回密码
   CWUPDATEUSERINFO,//用户信息修改
   CWADDUPDATEDRIVER,//驾驶员信息修改/新增
   CWQUERYDRIVER,//驾驶员信息查询
   CWDELETEDRIVER,//删除驾驶员信息
   CWAPPLYLOAN,//贷款申请
   CWQUERYLOANINFO,//贷款信息列表查询
   CWDELETELOANINFO ,//撤销贷款请求
    CWUPLOADRELATIVE//通讯录上传
} WKNetInterface;


@interface CWSingleSample : NSObject<ASIHTTPRequestDelegate>
+(CWSingleSample *)sharedSingleSample:(UIViewController *)myViewController;

@property (nonatomic,strong) MBProgressHUD* ssHUD;
@property (nonatomic,strong) UIViewController *myViewController;
/**
 *请求简化版
 */
-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock;
-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withValue:(NSDictionary *)value withFinish:(getDataBlock)dataBlock;

/**
 *统一的http请求,参数:请求的标示名称,请求的参数串,请求成功的回调,请求失败的回调
 */
-(void)myNetWork:(WKNetInterface)myInterface withValue:(NSDictionary *)value withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock withError:(getErrorBlock)errorBlock;
/**
 * 上传文件
 * @param flag 是否需要保存数据
 */
-(void)myUploadFile:(UIImage *)uploadImage withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock withFlag:(BOOL)flag;

/**
 *上传图片
 */
-(void)myUploadFile:(UIImage *)uploadImage withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock withFlag:(BOOL)flag;

/**
 * 文件上传
 * @param thUpFilePath 文件路径
 * @param url 服务器地址
 * @param finishBlock 请求成功
 * @param errorBlock 请求错误
 */
-(void)myUploadFile:(NSString *)theUpFilePath withFileUrl:(NSString *)url withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock;

/**
 *语音文件下载
 * @param url 请求地址
 * @param path 下载文件存放的路径
 */
-(void)downLoadVoiceUrl:(NSString *)url withDownloadPath:(NSString *)path;
@end

 CWSingleSample.m

//
//  CWSingleSample.m
//  students
//
//  Created by ZKSoft on 14/11/13.
//  Copyright (c) 2014年 ZK. All rights reserved.
//

#import "CWSingleSample.h"
 
@implementation CWSingleSample
static CWSingleSample *sharedSingleSample=nil;
+(CWSingleSample *)sharedSingleSample:(UIViewController *)myViewController{
    
    @synchronized(self)
    {
        if (!sharedSingleSample){
            sharedSingleSample = [[CWSingleSample alloc] init];
            sharedSingleSample.myViewController=myViewController;
            //初始化进度框,置于当前的View当中
            sharedSingleSample.ssHUD = [[MBProgressHUD alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
            [[[[UIApplication sharedApplication] delegate] window] addSubview:sharedSingleSample.ssHUD];
            
            //如果设置此属性则当前的view置于后台
            sharedSingleSample.ssHUD.dimBackground = YES;
            
        }
        return sharedSingleSample;
    }
}

-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock{
    [self myNetWork:myInterface withValue:nil withUrl:strUrl withFinish:dataBlock withError:nil];
}
-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withValue:(NSDictionary *)value withFinish:(getDataBlock)dataBlock{
    [self myNetWork:myInterface withValue:value withUrl:strUrl withFinish:dataBlock withError:nil];
}
-(void)myNetWork:(WKNetInterface)myInterface withValue:(NSDictionary *)value withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock withError:(getErrorBlock)errorBlock{
    //配置请求接口
    NSArray *interTemp=@[
                        @"smsSend",//短信验证码发送
                        @"userRegister",//用户注册
                        @"userLogin",//用户登录
                        @"passwordDeal",//密码修改/找回密码
                        @"updateUserInfo",//用户信息修改
                        @"addUpdateDriver",//驾驶员信息修改/新增
                        @"queryDriver",//驾驶员信息查询
                        @"deleteDriver",//删除驾驶员信息
                        @"applyLoan",//贷款申请
                        @"queryLoanInfo",//贷款信息列表查询
                        @"deleteLoanInfo",//撤销贷款请求
                        @"uploadRelative"//通讯录上传
                         ];
    value=value==nil?@{}:value;
    //配置请求
    NSURL *requestUrl=[NSURL URLWithString:CWBaseURLString];
    AFHTTPClient *client=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    
    if (myInterface==CWSMSSEND || myInterface==CWUSERREGISTER || myInterface==CWUSERLOGIN || myInterface==CWPASSWORDDEAL || myInterface==CWUPDATEUSERINFO || myInterface==CWADDUPDATEDRIVER || myInterface==CWQUERYDRIVER || myInterface==CWDELETEDRIVER || myInterface == CWAPPLYLOAN || myInterface==CWQUERYLOANINFO ||myInterface==CWDELETELOANINFO ||myInterface ==CWUPLOADRELATIVE) {
        [CWSS.ssHUD setLabelText:@"加载中"];
        [CWSS.ssHUD show:YES];
    }
 
         if (YES) {//post
        NSLog(@"post");
        [client postPath:[NSString stringWithFormat:@"TaxiLoanGate/LoanCtrlServlet?action=%@%@",[interTemp objectAtIndex:myInterface],strUrl] parameters:value success:^(AFHTTPRequestOperation *operation,id responseObject){
                [CWSS.ssHUD hide:YES];
            NSLog(@"url---%@",[[operation request] URL]);
            if (dataBlock) {
                id tempData=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                if ([[tempData objectForKey:@"success"] isEqualToString:@"0000"]) {
                    dataBlock(tempData);
                    
                }else{
//                   dataBlock(tempData);
                    if (myInterface==CWUSERLOGIN  || myInterface==CWUSERREGISTER ||myInterface==CWPASSWORDDEAL || myInterface==CWAPPLYLOAN || myInterface==CWDELETELOANINFO || myInterface==CWADDUPDATEDRIVER ||myInterface==CWDELETEDRIVER){
                        [cwutil myAlertView:[tempData objectForKey:@"respinfo"]];
                       
                    }else{
                        NSLog(@"%d--%@",myInterface,[[operation request] URL]);
                    }
                }
                
            }
            [CWSS.ssHUD hide:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [CWSS.ssHUD hide:YES];
            if (errorBlock) {
                errorBlock(error);
            }else{
                NSLog(@"%d--%@--%@",myInterface,[[operation request] URL],error);
            }
        }];
    }else{//get
        [client getPath:[NSString stringWithFormat:@"TaxiLoanGate/LoanCtrlServlet?action=%@%@",[interTemp objectAtIndex:myInterface],strUrl] parameters:value success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [CWSS.ssHUD hide:YES];
            if (dataBlock) {
                dataBlock([NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [CWSS.ssHUD hide:YES];
            if (errorBlock) {
                errorBlock(error);
            }else{
                NSLog(@"%d-><-%@--%@",myInterface,[[operation request] URL],error);
            }
        }];
    }
}

/**
 * 上传图片
 */
-(void)myUploadFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock{
    NSURL *requestUrl=[NSURL URLWithString:[[CWBaseURLString stringByAppendingFormat:@"RemoteUpload.aspx?vercode=123456&operation=iosupload"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPClient *httpClient=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    NSData *imageData=UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
    
    NSMutableURLRequest *request=[httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData){
        [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpg"];
    }];
    
    AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWrittrn,long long totalBytesWritten,long long totalBytesExpectedToWrite){
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    }];
    [operation start];
}

/**
 * 上传文件
 * @param flag 是否需要保存数据
 */
-(void)myUploadFile:(UIImage *)uploadImage withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock withFlag:(BOOL)flag{
    
    NSURL *requestUrl=[NSURL URLWithString:[[CWBaseURLString stringByAppendingString:@""] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    [CWSS.ssHUD setLabelText:@"正在上传"];
    [CWSS.ssHUD show:YES];
    AFHTTPClient *httpClient=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    
    NSMutableURLRequest *request=[httpClient multipartFormRequestWithMethod:@"POST" path:@"/RemoteUpload.ashx?vercode=123456&operation=iosupload&Filename=head.png" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>formData){
        NSData *data=UIImageJPEGRepresentation(uploadImage, 0.4);
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory=[paths objectAtIndex:0];
        
        ///上传头像
        NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"temp_head.jpg"]];
        [data writeToFile:savedImagePath atomically:NO];
        
        [formData appendPartWithFileData:data name:@"filename" fileName:savedImagePath mimeType:@"image/jpg"];
        
    }];
    
    AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responseObject){
        if (finishBlock) {
            finishBlock([[operation userInfo] objectForKey:@"filename"],[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]);
            
//            if (flag==YES) {
//                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:nil];
//                NSLog(@"dic---%@",[dic objectForKey:@"data"]);
//                if ([[ZKNSUserDefaults initUserDefaults].userDefaults objectForKey:UPLOADIMAGE]) {
//                    [ZKNSUserDefaults deleteUserDefaultsData:UPLOADIMAGE];
//                }
//                //保存头像
//                [ZKNSUserDefaults createUserDefaultDB:UPLOADIMAGE getArrayData:[dic objectForKey:@"data"]];
//            }
            NSLog(@"上传成功");
            [CWSS.ssHUD setLabelText:@"上传成功"];
            [CWSS.ssHUD hide:YES afterDelay:2.0f];
        }
    } failure:^(AFHTTPRequestOperation *operation,NSError *error){
        if (errorBlock) {
            errorBlock(error);
            NSLog(@"上传失败");
            [CWSS.ssHUD setLabelText:@"上传失败"];
            [CWSS.ssHUD hide:YES afterDelay:2.0f];
        }
    }];
    [httpClient enqueueHTTPRequestOperation:operation];
}

/**
 * 上次用于语音文件的上传
 */
-(void)myUploadFile:(NSString *)theUpFilePath withFileUrl:(NSString *)url withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock{
    NSURL *requestUrl=[NSURL URLWithString:[[CWBaseURLString stringByAppendingString:@""] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    AFHTTPClient * client=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    NSMutableURLRequest *fileUpRequest=[client multipartFormRequestWithMethod:@"POST" path:[NSString stringWithFormat:@"ichat.aspx?vercode=123456%@",url] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSError *error;
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:theUpFilePath isDirectory:NO] name:@"file" fileName:@"textMusic.mp3" mimeType:@"audio/mp3" error:&error];
        NSLog(@"errorBlock---%@",error);
    }];
    
    AFHTTPRequestOperation *fileUploadOp=[[AFHTTPRequestOperation alloc] initWithRequest:fileUpRequest];
    [fileUploadOp setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"upload finish ---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error---%@",error);
    }];
    
    [client enqueueHTTPRequestOperation:fileUploadOp];
}

/**
 *语音文件下载
 * @param url 请求地址
 * @param path 下载文件存放的路径
 */
-(void)downLoadVoiceUrl:(NSString *)url withDownloadPath:(NSString *)path{
    NSURL *urlString = [NSURL URLWithString:[NSString stringWithFormat:@"%@Download.ashx?vercode=123456%@",CWBaseURLString,url]];
    
    NSLog(@"url---%@",urlString);
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:urlString];
    request.delegate=self;
    //当request完成时,整个文件会被移动到这里
    [request setDownloadDestinationPath:path];
    //这个文件已经被下载了一部分
    //                        [request setTemporaryFileDownloadPath:[NSString stringWithFormat:@"%@%@",NSTemporaryDirectory(),[[[[[data objectForKey:@"data"] objectForKey:@"MsgList"][i] objectForKey:@"Content"] componentsSeparatedByString:@":"][2] stringByReplacingOccurrencesOfString:@"]" withString:@""]]];
    [request setAllowResumeForFileDownloads:YES];//是否允许断点下载
    [request startSynchronous];
    
    NSLog(@"path---%@",path);
}

#pragma mark ASIHTTPRequestDelegate
-(void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"下载失败");

}
-(void)requestFinished:(ASIHTTPRequest *)request{
    NSLog(@"下载成功");

}


@end

 在pch文件中需要定义常量:

#define CWBaseURLString @"http://172.16.128.174:8080/"
//网络单例类的调用
#define CWSS [CWSingleSample sharedSingleSample:sharedSingleSample.myViewController]

                                                                                              此次修改:2015-3-27    未完待续...

原文地址:https://www.cnblogs.com/boyuanmeng/p/4371705.html