首页 > 代码库 > 使用NSURLConnection的网络请求与封装
使用NSURLConnection的网络请求与封装
访问网络的方式:
1、同步请求: 会阻塞主线程
2、异步请求: 无法取消 请求过程在多线程执行
基本流程:
1、构造NSURL实例。
2、生成NSURLRequest请求。
3、通过NSURLConnection发送请求。
4、通过NSURLRespond实例和NSError实例分析结果。
5、接受返回数据。
使用NSURLConnection发起异步请求:
第一种方法:
- (void)setUrl:(NSURL *)url
{
//使用同异步请求网络
NSMutableURLRequest *request = [[NSMutableURLRequestalloc]init];
[requestsetHTTPMethod:@"GET"];//设置请求方式
[requestsetURL:url]; //设置网络请求的url
[request setTimeoutInterval:60];//设置超出时间
//get请求不需要设置请求体
self.data = [NSMutableDatadata];
[NSURLConnectionconnectionWithRequest:request delegate:self];
}
//此种方法可以通过协议方法来监听数据加载的过程
几种常用的协议方法:
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.dataappendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *image = [UIImageimageWithData:self.data];
self.image = image;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"请求失败!!!");
}
第二种方法:- (void)setImageWithURL:(NSURL *)url
{
#if 0
//使用同步请求网络
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setHTTPMethod:@"GET"];
[request setURL:url];
[request setTimeoutInterval:60];
//get请求不需要设置请求体
NSURLResponse *response;
//发送同步请求
NSData *data = http://www.mamicode.com/[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
UIImage *image = [UIImage imageWithData:data];
self.image = image;
#endif
#if 1
//使用异步请求网络
NSMutableURLRequest *request = [[NSMutableURLRequestalloc]init];
[requestsetHTTPMethod:@"GET"];
[requestsetURL:url];
[request setTimeoutInterval:60];
//get请求不需要设置请求体
// NSURLResponse *response;
//发送异步请求
NSOperationQueue *queue = [[NSOperationQueuealloc]init];
[NSURLConnectionsendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError)
{
UIImage *image = [UIImageimageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
self.image = image; //主线程加载数据
});
}];
#endif
}
下面简单写一个NSURLConnection的封装代码
首先写封装 NSMutableURLRequest的代码 得继承它
#import <Foundation/Foundation.h>
typedefvoid(^FinshLoadBlock) (NSData *);
@interface PXRequest :NSMutableURLRequest <NSURLConnectionDataDelegate>
@property (nonatomic,strong)NSMutableData *data; //加载的数据
@property (nonatomic,strong)NSURLConnection *connection;//连接对象
@property (nonatomic,strong)FinshLoadBlock block; //定义一个block数据加载完后调用
- (void)startAsynrc;//开始请求
- (void)cancel; //取消请求
@end
#import "PXRequest.h"
@implementation PXRequest
//开始异步请求
- (void)startAsynrc
{
self.data = [NSMutableDatadata];
self.connection = [NSURLConnectionconnectionWithRequest:selfdelegate:self];
}
- (void)cancel
{
[self.connectioncancel];
}
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.dataappendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.block(_data);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"出错信息 = %@",error);
}
@end
下面封装一段数据代码:
比如我要通过网络去访问一段天气接口
#import <Foundation/Foundation.h>
typedef void(^Completion)(id result);//返回void 参数id 名字Completion
@interface PXDataService :NSObject
//访问天气接口数据
+ (void)getWetheaData:(NSDictionary *)params block:(Completion)block;
@end
#import "PXDataService.h"
#import "PXRequest.h"
#define BASE_URL @"http://www.weather.com.cn/data/sk/"
@implementation PXDataService
//定义获取天气的接口
+ (void)getWetheaData:(NSDictionary *)params block:(Completion)block
{
NSString *cityCode = [params objectForKey:@"code"];
NSString *urlstring = [BASE_URLstringByAppendingFormat:@"%@.html",cityCode];
[selfstartRequest:params url:urlstring block:block isGet:NO];
}
+ (void)startRequest:(NSDictionary *)param
url:(NSString *)urlString
block:(Completion)block
isGet:(BOOL)get
{
PXRequest *request = [PXRequestrequestWithURL:[NSURLURLWithString:urlString]];
if(get)
[requestsetHTTPMethod:@"GET"];
else
[requestsetTimeoutInterval:60];
//如果是post请求则需要有请求体一般格式是 username=zpx&password=1234
// [request setHTTPBody:<#(NSData *)#>]
[requeststartAsynrc]; //开始请求网络
//当request的block执行时会执行这里面的代码 block封装一段代码
request.block = ^(NSData *data){
NSString *datastring = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"data = http://www.mamicode.com/%@",datastring);
id ret = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:nil];
//json解析
block(ret);
};
}
@end
主函数代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColorwhiteColor];
[self.windowmakeKeyAndVisible];
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeContactAdd];
button.frame =CGRectMake(10,50, 20, 20);
[button addTarget:selfaction:@selector(load)forControlEvents:UIControlEventTouchUpInside];
[self.windowaddSubview:button];
return YES;
}
- (void)load
{
NSDictionary *params =@{@"code":@"101010300"};
[PXDataServicegetWetheaData:params block:^(id result) {
NSLog(@"result = %@",result); //打印加载完的数据
}];
}
点击按钮打印:2014-07-08 23:08:20.862 WXDataServer[11527:60b] result = {
weatherinfo = {
Radar = "JC_RADAR_AZ9010_JB";
SD = "70%";
WD = "\U5317\U98ce";
WS = "0\U7ea7";
WSE = 0;
city = "\U671d\U9633";
cityid = 101010300;
isRadar = 1;
temp = 24;
time = "22:55";
};
}