您的位置:首页 > 理论基础 > 计算机网络

NetWorkTool工具类之网络请求

2015-10-01 14:17 459 查看
NetWorkTool.h

#pragma mark这个类通过block的方法,把这个类请求的数据,返回到视图控制器.

typedef void(^ Block)(id result);

@interface NetWorkTool : NSObject

-(void)netWorkingWithURL:(NSString *)strURL block:(Block)block;

+(void)netWorkingWithURL:(NSString *)strURL block:(Block)block;

//实现POST请求

+(void)netWorkingWithURL:(NSString *)strURL body:(NSString *)strbody block:(Block)block;

NetWorkTool.h

-(void)netWorkingWithURL:(NSString *)strURL block:(Block)block{

NSString *strEncode=[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url=[NSURL URLWithString:strEncode];

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {id result=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

//把json处理好的数据,通过block进行回调,返回到视图控制器

block(result);}];}

+(void)netWorkingWithURL:(NSString *)strURL block:(Block)block{

NSString *strEncode=[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url=[NSURL URLWithString:strEncode];

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {id result=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

//把json处理好的数据,通过block进行回调,返回到视图控制器

block(result);}];}

+(void)netWorkingWithURL:(NSString *)strURL body:(NSString *)strbody block:(Block)block{

NSString *strEncode=[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url=[NSURL URLWithString:strEncode];

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

NSData *data1=[strbody dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data1];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {id result=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers
error:nil];

block(result);}];}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: