ios 网络请求数据封装类

来源:互联网 发布:为什么会有网络诈骗 编辑:程序博客网 时间:2024/06/04 18:02


////////////////////////////////////////////////////////////////

// 请求基类

////////////////////////////////////////////////////////////////


#import <Foundation/Foundation.h>

#import "ASIFormDataRequest.h"


@interface CKRequestModel :NSObject

{

    ASIFormDataRequest *_request;

   NSDictionary *_jsonDict;

}


// 开始请求, 供派生类调用

- (void)startRequestWithStrUrl:(NSString *)strUrl

             postKeysAndValues:(NSDictionary *)dict;


// 取消请求, UI调用

- (void)cancelRequest;

// 成功回调, 供派生类重载

- (void)onRequestDidFinish:(ASIHTTPRequest *)request;

// 失败回调, 供派生类重载

- (void)onRequestDidFail:(ASIHTTPRequest *)request;

@end


#import "CKRequestModel.h"


@implementation CKRequestModel


- (void)startRequestWithStrUrl:(NSString *)strUrl

             postKeysAndValues:(NSDictionary *)dict

{

    _request = [[ASIFormDataRequestalloc] initWithURL:[NSURLURLWithString:strUrl]];

    _request.delegate =self;

       /*

     如果要设置globaltimeout机制,例如自定义的计时器不好用的话,就是用:

      _request.timeOutSeconds = 10;

     回调检查:

     - (void)requestFailed:(ASIHTTPRequest *)request {

     NSLog(@"Error: %@",[[request error] localizedDescription]);

     }

     */

    [_requestsetDidFinishSelector:@selector(onRequestDidFinish:)];

    [_requestsetDidFailSelector:@selector(onRequestDidFail:)];

    

   for (NSString *keyin dict)

    {

       if([dict[key]length]>0)

            [_requestaddPostValue:dict[key] forKey:key];

    }

    [_requeststartAsynchronous];

    NSLog(@"===<HTTP>开始===:%@",_request.url);

}


- (void)onRequestDidFinish:(ASIHTTPRequest *)request

{

    NSString *str = [NSStringstringWithCString:[[request responseData]bytes] encoding:NSUTF8StringEncoding ];

    NSLog(@"===<HTTP>成功,收到数据===:%@", str );

   NSString *response = [request responseString];

    NSString *string1 = [responsestringByReplacingOccurrencesOfString:@"\r"withString:@""];

    NSString *string2 = [string1stringByReplacingOccurrencesOfString:@"\n"withString:@""];

    NSString *string3 = [string2stringByReplacingOccurrencesOfString:@" "withString:@""];

    NSData *data = [string3dataUsingEncoding:NSUTF8StringEncoding];

    

    _jsonDict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableLeaveserror:nil];

#ifdef LOG_ALL_RECEIVED_DATA

    NSLog(@"===<HTTP>JSON解析后===:%@",_jsonDict);

#endif


}


- (void)onRequestDidFail:(ASIHTTPRequest *)request

{

    NSLog(@"===<HTTP>失败===:%@",_request.url);

   UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"网络请求失败" delegate:nilcancelButtonTitle:@"确定" otherButtonTitles:nil,nil];

    [alertshow];

}


- (void)cancelRequest

{

    [_requestclearDelegatesAndCancel];

}


@end




原创粉丝点击