iOS 封装网络请求体,post请求方式

2016-07-06  本文已影响1355人  可乐小子

在我们看到比如淘宝网或者其他的app,在进入一个页面,还没有完全加载进去的时候,当前的app是卡线程的,也就是同步加载的数据,而我们在上传或者下载数据的时候,往往会用到get或者post请求方式,那么我们就可以自身封装一个网络请求方式,就像淘宝网app这样的,可以在进入一个页面的时候,同步加载数据,直到数据加载完成才展示我们的UI控件.

下面是代码部分:

+ (void)httpRequestUrl:(NSString *)requestUrl    httpMethod:(NSString *)method  httpBody:(NSMutableDictionary *)body   normal:(BOOL)isNormal  asynchronous:(BOOL)isAsynchronous  callBack:(CallBack)callBack{

[Macro  Log:requestUrl];  // 内部封装的类方法,用于打印请求的网址

NSUrl * url = [[NSUrl  URLWithString:[requestUrl  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];     

NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];   

[urlRequest setHTTPMethod:method.length?method:HTTP_GET];   // 如果是请求方式(get还是post)

if (isNormal)

{

[urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSMutableString *authorization=[NSMutableString string];

[authorization appendString:MD5_KEY];

[authorization appendString:requestUrl];

[urlRequest addValue:[authorization MD5String] forHTTPHeaderField:@"Authorization"];

NSMutableString *accept=[NSMutableString string];

[accept appendFormat:@"version:%@,channelType:2,lat:%f,lon:%f",SHARE_USER_CONTEXT.version.versionNo,SHARE_USER_CONTEXT.userLocation.coordinate.latitude,SHARE_USER_CONTEXT.userLocation.coordinate.longitude];

[urlRequest addValue:accept forHTTPHeaderField:@"Accept"];

}

if (body) {

NSString *bodyString=[body JSONString];

[urlRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];

}

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

operation.responseSerializer=[AFJSONResponseSerializer serializer];

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

if (!isAsynchronous)

{

//            [Macro unFreezeScreen];

[Macro unLoadAnimation];

}

[PutData putdataName:@"成功响应:" ContentId:responseObject];

callBack(responseObject);

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

if (!isAsynchronous)

{

//            [Macro unFreezeScreen];

[Macro unLoadAnimation];

}

if (isAsynchronous)// 每45s上传坐标的接口传值为YES

{

}

else

{

if (operation.responseString.length)

{

AlertShow(nil, operation.responseString);

}

else

{

AlertShow(nil, [error localizedDescription]);

}

}

[PutData putdataName:@"出错响应:" ContentId:operation.responseString];

callBack(operation.responseString);

[PutData putdataName:@"出错原因:" ContentId:[error localizedDescription]];

[PutData putdataName:@"出错原因:" ContentId:requestUrl];

[Macro Log:[error localizedDescription]];

}];

if (!isAsynchronous)

{

//        [Macro freezeScreen];

[Macro loadAnimation:@"正在加载..."];

}

[[NSOperationQueue mainQueue] addOperation:operation];

}


ok,那封装了的数据请求之后,就是怎么使用了,以添加费用详情单model为例,我是在上传之前,直接把一个需要的数据放置在model内,然后再把model上传,因为服务器是可以接受可变字典这样的变量的

代码:

+ (void)addDriverFeeMonthDetailWithAsynch:(BOOL)asynch AddDriverFeeMonthDetailModel:(DateModel *)FeeMonthModel callBack:(CallBack)callBack

{

NSString *urlString;

urlString = [NSString stringWithFormat:@"%@/SubmitDriverFeeMonth" , SHARE_USER_CONTEXT.urlList.BASE_HOST];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setObject:[NSNumber numberWithInteger:FeeMonthModel.MonthID] forKey:@"MonthID"];

[dict setObject:[NSNumber numberWithInteger:FeeMonthModel.PostMonth] forKey:@"PostMonth"];

[dict setObject:[NSNumber numberWithInteger:FeeMonthModel.PostYear] forKey:@"PostYear"];

[dict setObject:[NSNumber numberWithInteger:FeeMonthModel.PicId] forKey:@"PicId"];  // picid,picurl  在修改的时候可以不上传,也就是不赋值即可

if (FeeMonthModel.PicUrl) {

[dict setObject:FeeMonthModel.PicUrl forKey:@"PicUrl"];

}

[dict setObject:[NSNumber numberWithDouble:FeeMonthModel.DriverBonus] forKey:@"DriverBonus"];

if (!FeeMonthModel.DriverBonusRemark.length || [FeeMonthModel.DriverBonusRemark isKindOfClass:[NSNull class]]) {

FeeMonthModel.DriverBonusRemark = @"";

}

[dict setObject:FeeMonthModel.DriverBonusRemark forKey:@"DriverBonusRemark"];

if (!FeeMonthModel.DriverName.length || [FeeMonthModel.DriverName isKindOfClass:[NSNull class]] ) {

FeeMonthModel.DriverName = @"";

}

[dict setObject:FeeMonthModel.DriverName forKey:@"DriverName"];

if (!FeeMonthModel.DriverNo.length || [FeeMonthModel.DriverNo isKindOfClass:[NSNull class]]) {

FeeMonthModel.DriverNo = @"";

}

[dict setObject:FeeMonthModel.DriverNo forKey:@"DriverNo"];

if (!FeeMonthModel.DriverPhone.length || [FeeMonthModel.DriverPhone isKindOfClass:[NSNull class]]) {

FeeMonthModel.DriverPhone = @"";

}

[dict setObject:FeeMonthModel.DriverPhone forKey:@"DriverPhone"];

if (FeeMonthModel.TotalAmount) {

[dict setObject:[NSNumber numberWithDouble:FeeMonthModel.TotalAmount] forKey:@"TotalAmount"];

}

if ([FeeMonthModel.LocalMoneyRemark isKindOfClass:[NSNull class]] || !FeeMonthModel.LocalMoneyRemark.length) {

FeeMonthModel.LocalMoneyRemark = @"";

}

[dict setObject:FeeMonthModel.LocalMoneyRemark forKey:@"LocalMoneyRemark"];

if (!FeeMonthModel.OrderNo.length || [FeeMonthModel.OrderNo isKindOfClass:[NSNull class]]) {

FeeMonthModel.OrderNo = @"";

}

[dict setObject:FeeMonthModel.OrderNo forKey:@"OrderNo"];

if (!FeeMonthModel.OtherMoneyRemark.length || [FeeMonthModel.OtherMoneyRemark isKindOfClass:[NSNull class]]) {

FeeMonthModel.OtherMoneyRemark = @"";

}

[dict setObject:FeeMonthModel.OtherMoneyRemark forKey:@"OtherMoneyRemark"];

if (FeeMonthModel.UltraKmActual) {

[dict setObject:[NSNumber numberWithDouble:FeeMonthModel.UltraKmActual] forKey:@"UltraKmActual"];

}

if (FeeMonthModel.UltraKmEnd) {

[dict setObject:[NSNumber numberWithDouble:FeeMonthModel.UltraKmEnd] forKey:@"UltraKmEnd"];

}

if (FeeMonthModel.UltraKmStart) {

[dict setObject:[NSNumber numberWithDouble:FeeMonthModel.UltraKmStart] forKey:@"UltraKmStart"];

}

[dict setObject:FeeMonthModel.DetailList forKey:@"DetailList"];

if (!FeeMonthModel.AcctName.length || [FeeMonthModel.AcctName isKindOfClass:[NSNull class]]) {

FeeMonthModel.AcctName = @"";

}

[dict setObject:FeeMonthModel.AcctName forKey:@"AcctName"];

[self httpRequestUrl:urlString httpMethod:HTTP_POST httpBody:dict normal:YES asynchronous:asynch callBack:callBack];

}

当然也是可以加一些非空判断的安全处理,比如

我把上传或者从服务器加载的数据model,通过加载非空的方法,来把空值赋予@“”,这样就不会崩掉了:

- (NSMutableDictionary *)getUnnullDict:dict{

// 传入一个字典,通过遍历得到内部的value,来处理空的value

for (NSString *key   in   dict.allKeys){

if([dict  objectForKey:key] isEqual:[NSNull  null]){

[dict  setValue:@""    forKey:key];

}

}

return   dict;

}

上一篇下一篇

猜你喜欢

热点阅读