#import <Foundation/Foundation.h>
#import "ASIFormDataRequest.h"
typedef void(^RequestFinishedBlock)(id result);
@interface NetService : NSObject
+(ASIHTTPRequest*)requestWithURL:(NSString*)urlString params:(NSMutableDictionary*)params httpMethod:(NSString*)httpMethod completeBlock:(RequestFinishedBlock)block;
@end
#import "NetService.h"
#import "URLConfig.h"
#import "commonConfig.h"
@implementation NetService
+(ASIHTTPRequest*)requestWithURL:(NSString*)urlString params:(NSMutableDictionary*)params httpMethod:(NSString*)httpMethod completeBlock:(RequestFinishedBlock)block
{
if ([httpMethod caseInsensitiveCompare:@"POST"] ==NSOrderedSame)
{
NSMutableString *finalurl=[NSMutableString stringWithFormat:@"HOST_URL%@?token=%@&sys=%@",urlString,[commonConfig sharedInstance].token,@"iphone"];
NSURL *url=[NSURL URLWithString:finalurl];
__block ASIFormDataRequest * request=[ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:httpMethod];
NSArray *allkeys=[params allKeys];
for (int i=0; i<[allkeys count]; i++)
{
NSString *key=[allkeys objectAtIndex:i];
id value=[params objectForKey:key];
if ([value isKindOfClass:[NSData class]])
{
//post file
[request addData:value forKey:key];
}else
{
[request addPostValue:value forKey:key];
}
}
[request setCompletionBlock:^{
NSData *data=[request responseData];
id result=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (block!=nil) {
block(result);
}
}];
[request startAsynchronous];
return request;
}else if([httpMethod caseInsensitiveCompare:@"GET"]==NSOrderedSame)
{
NSMutableString *paramString=[NSMutableString string];
NSArray *allkeys=[params allKeys];
for (int i=0;i<[allkeys count]; i++)
{
NSString *key=[allkeys objectAtIndex:i];
id value=[params objectForKey:key];
[paramString appendFormat:@"%@=%@&",key,value];
}
[paramString appendFormat:@"token=%@&sys=%@",[commonConfig sharedInstance].token,@"iphone"];
NSMutableString *finalurl=[NSMutableString stringWithFormat:@"%@%@%@",HOST_URL,urlString,paramString];
NSLog(@"%@",finalurl);
NSURL *url=[NSURL URLWithString:finalurl];
__block ASIFormDataRequest *request=[ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:httpMethod];
[request setCompletionBlock:^{
NSData *data=[request responseData];
id result=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (block!=nil) {
block(result);
}
}];
[request startAsynchronous];
return request;
}
return nil;
}
@end
[NetService requestWithURL:DOCTOR_LOGIN params:dic httpMethod:@"GET" completeBlock:^(id result)
{
NSLog(@"%@",result);
}];
对于ASIHTTPRequest的封装,布布扣,bubuko.com
原文:http://blog.csdn.net/richard_rufeng/article/details/23137423