NetWorkTool工具类之网络请求

本文介绍了一个iOS平台上的网络请求工具类,使用Block进行数据回调,支持GET和POST请求,并解析JSON响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);}];}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值