您的位置:首页 > 其它

NSURLConnection使用

2015-08-07 20:13 190 查看
通过NSURLConnection进行异步下载

NSURLConnection
提供了两种方式来实现连接,一种是同步的还有一种是异步的,异步的连接将会创建一个新的线程,这个线程将会来负责下载的动作。而对于同步连接,在下载连接和处理通讯时,则会堵塞当前调用线程。

很多开发人员都会觉得同步的连接将会阻塞主线程,其实这样的观点是错误的。一个同步的连接是会阻塞调用它的线程。假设你在主线程中创建一个同步连接,没错,主线程会阻塞。可是假设你并非从主线程开启的一个同步的连接,它将会类似异步的连接一样。因此这样的情况并不会阻塞你的主线程。

其实,同步和异步的主要差别就是执行
runtime
为会异步连接创建一个线程,而同步连接则不会。

//asynchronousRequest connection
-(void)fetchAppleHtml{
NSString *urlString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlString];
//    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0f]; //maximal timeout is 30s

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([data length] > 0 && connectionError == nil) {
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDir stringByAppendingPathComponent:@"apple.html"];
[data writeToFile:filePath atomically:YES];
NSLog(@"Successfully saved the file to %@",filePath);
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@",html);
}else if ([data length] == 0 && connectionError == nil){
NSLog(@"Nothing was downloaded.");
}else if (connectionError != nil){
NSLog(@"Error happened = %@",connectionError);
}
}];
}


通过NSURLConnection进行同步下载

使用
NSURLConnection
的 sendSynchronousRequest:returningResponse:error:类方法,我们能够进行同步请求。

在创建一个同步的网络连接的时候我们须要明确一点,并非是我们的这个同步连接一定会阻塞我们的主线程,假设这个同步的连接是创建在主线程上的,那么这样的情况下是会阻塞我们的主线程的,其它的情况下是不一定会阻塞我们的主线程的。假设你在
GCD 的全局并发队列上初始化了一个同步的连接,你事实上并不会阻塞我们的主线程的。

我们来初始化第一个同步连接,并看看会发生什么。在实例中,我们将尝试获取
Yahoo!美国网站主页内容:

//synchronousRequest connection
-(void)fetchYahooData{
NSLog(@"We are here...");
NSString *urlString = @"http://www.yahoo.com";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSLog(@"Firing synchronous url connection...");
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if ([data length] > 0 && error == nil) {
NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);
}else if([data length] == 0 && error == nil){
NSLog(@"No data was return.");
}else if (error != nil){
NSLog(@"Error happened = %@",error);
}
NSLog(@"We are done.");

}
/*
|
| as we know, it will chock main thread when we call sendSynchronousRequest on main thread,,,,change below
|
v
*/
//call sendSynchronousRequest on GCD pool
-(void)fetchYahooData2_GCD{
NSLog(@"We are here...");
NSString *urlString = @"http://www.yahoo.com";
NSLog(@"Firing synchronous url connection...");
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^{
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if ([data length] > 0 && error == nil) {
NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);
}else if ([data length] == 0 && error == nil){
NSLog(@"No data was returned.");
}else if (error != nil){
NSLog(@"Error happened = %@",error);
}
});
NSLog(@"We are done.");

}


查看执行输出结果。分别为:

synchronous download on main thread without GCD



synchronous download on main thread with GCD



能够看到在主线程上调用同步下载会堵塞当前线程,而使用GCD则不会。

通过NSURLConnection发送一个HTTP GET请求

//send a GET request to server with some params
-(void)httpGetWithParams{
NSString *urlString = @"http://chaoyuan.sinaapp.com";
urlString = [urlString stringByAppendingString:@"?

p=1059"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([data length] > 0 && connectionError == nil) {
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@",html);
}else if([data length] == 0 && connectionError == nil){
NSLog(@"nothing was download.");
}else if(connectionError != nil){
NSLog(@"Error happened = %@",connectionError);
}
}];
}


[b] 通过NSURLConnection发送一个HTTP POST请求[/b]

//send a POST request to a server with some params
-(void)httpPostWithParams{
NSString *urlAsString = @"http://chaoyuan.sinaapp.com";
urlAsString = [urlAsString stringByAppendingString:@"?

param1=First"];
urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"POST"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2"; [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue completionHandler:^(NSURLResponse *response, NSData *data,
NSError *error) {
if ([data length] >0 &&
error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html);
}
else if ([data length] == 0 &&
error == nil){
NSLog(@"Nothing was downloaded.");
}
else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
}


tips:

except http get and post there are http delete and put and something else, if you are crazy about http, please GOOGLE!

完整项目代码在这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: