ASIHTTPRequest 对GET POST 请求简单封装
1.ASIHTTPRequest简介
github下载地址https://github.com/pokeb/asi-http-request
2.ASIHTTPRequest 对GET和POST请求简单封装
+(void)requestWithASIURL:(NSString *)urlString parmas:(NSMutableDictionary *)params httpMethod:(NSString *)method completeBlock:(RequestFinishBlock)block{ //处理GET请求 if ([[method uppercaseString] isEqualToString:@"GET"]) { NSArray *keys=[params allKeys]; for (int i=0; i<keys.count; i++) { NSString *key=[keys objectAtIndex:i]; NSString *values=[params valueForKey:key]; urlString= [urlString stringByAppendingFormat:@"&%@=%@",key,values]; } } NSURL *url=[NSURL URLWithString:urlString]; ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url]; [request setRequestMethod:method]; [request setTimeOutSeconds:10]; //处理POST请求 if ([[method uppercaseString] isEqualToString:@"POST"]) { NSArray *keys=[params allKeys]; for (int i=0; i<keys.count; i++) { NSString *key=[keys objectAtIndex:i]; NSString *value=[params objectForKey:key]; if ([value isKindOfClass:[UIImage class]]) { // NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test4" ofType:@"gif"]; // NSData* data=[NSData dataWithContentsOfFile:filePath]; NSData *imageData=UIImageJPEGRepresentation(value, 1.0); [request addData:imageData forKey:key]; } [request setPostValue:value forKey:key]; } } [request setCompletionBlock:^{ NSData *data=[request responseData]; NSJSONSerialization *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; block(json); }]; [request startAsynchronous]; }
3.调用格式
NSString* urlString=@"http://192.168.1.101:8080/PengFu/jokController/getPhoneJok"; NSMutableDictionary *params=[NSMutableDictionary dictionaryWithObject:@"1 " forKey:@"rows"]; UIImage *image=[UIImage imageNamed:@"test3.gif"]; [params setObject:image forKey:@"pic"]; [params setObject:@"test gif image upload" forKey:@"status"]; [DataService requestWithASIURL:urlString1 parmas:params httpMethod:@"POST" completeBlock:^(id result) { NSLog(@"%@",result); }];
4.注意事项
下载代码编译报错请先导入网络请求所需的5个库如下
如果使用ARC自动内存管理,请在源码编译后面加-fno-objc-arc,如下图