//----------------------TCNetworkBaseFirstViewController.h
#import <UIKit/UIKit.h>
@interface TCNetworkBaseFirstViewController : UIViewController
@end
//----------------------TCNetworkBaseFirstViewController.m
#import "TCNetworkBaseFirstViewController.h"
#import "FirstNetWorkObject.h"
@interface TCNetworkBaseFirstViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@end
@implementation TCNetworkBaseFirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
FirstNetWorkObject *firstNetwork = [[FirstNetWorkObject alloc]init];
//普通网络请求
NSString *urlString = @"http://www.atool.org/email_image.php";
//--基础URL
[firstNetwork doURLWith:urlString];
//--同步请求
[firstNetwork doSyncRequest:urlString];
//--队列请求
[firstNetwork doQueuedRequest:urlString delegate:nil];
//--异步请求
[firstNetwork startRequestWithURLString:urlString];
}
@end
//----------------------FirstNetWorkObject.h
#import <Foundation/Foundation.h>
@interface FirstNetWorkObject : NSObject
//TODO: URL
- (void)doURLWith:(NSString *)urlString;
//TODO: 同步请求
- (void)doSyncRequest:(NSString *)urlString;
//TODO: 队列异步请求
- (void)doQueuedRequest:(NSString *)urlString delegate:(id)delegate;
//TODO: 异步请求
- (void)startRequestWithURLString:(NSString *)urlString;
@end
//----------------------FirstNetWorkObject.m
#import "FirstNetWorkObject.h"
@interface FirstNetWorkObject()<NSURLConnectionDataDelegate>
{
NSOperationQueue *_queue;
NSURL *_url;
NSURLConnection *_connection;
}
@end
@implementation FirstNetWorkObject
//TODO: URL
- (void)doURLWith:(NSString *)urlString
{
//---Base
/*
@ NSURL
*/
NSURL *url = [NSURL URLWithString:urlString];
if (url == nil) {
NSLog(@"url is nil .");
return;
}
NSLog(@"port: %@",url.port);
NSLog(@"host: %@",url.host);
NSLog(@"path: %@",url.path);
/*
@ NSURLRequest
包含加载URL内容所需要的信息;
支持HTTP、HTTPS、FTP、FILE URL;
*/
//三种请求方式 - 利用 #define .... #ifdef .... #else 区分
//#define defaultRequest //1 普通
//#define defaultMutableRequest //2 自定义缓存与超时值创建request
//#define requestBody //3 设置Body
#ifdef defaultRequest //-----1
//系统默认
NSURLRequest *request = [NSURLRequest requestWithURL:url];
#else //-----1
#ifdef defaultMutableRequest //-----2
//自定义缓存与超时值创建request
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.f];
#else //-----2
//NSMutableURLRequest是NSURLRequest的字类,可修改请求属性
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
#ifdef requestBody //-----3
[request setHTTPBody:[@"body" dataUsingEncoding:NSUTF8StringEncoding]];
#else //-----3
//输入流(使用输入流提供请求体而无须将整个体加载到内存中)发送诸如照片、视频等大量内容的最佳选择
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:@"文件路径"];
[request setHTTPBodyStream:inputStream];
#endif //3
#endif //2
#endif //1
if (request == nil) {
NSLog(@"request is nil .");
return;
}
}
//TODO: 同步请求
- (void)doSyncRequest:(NSString *)urlString
{
NSURL *url = [NSURL URLWithString:urlString];
//缓存策略:永不缓存
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.f];
NSHTTPURLResponse *response;
NSError *error = nil;
/*
NSURLConnection
*/
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
NSLog(@"error on load = %@",[error localizedDescription]);
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode != 200) {
NSLog(@"code = %@",[NSNumber numberWithInteger:httpResponse.statusCode]);
return;
}
}
NSString *xml = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",xml);
}
//TODO: 队列异步请求
- (void)doQueuedRequest:(NSString *)urlString delegate:(id)delegate
{
NSURL *url = [NSURL URLWithString:urlString];
//缓存策略:永不缓存
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.f];
if (!_queue) {
_queue = [[NSOperationQueue alloc] init];
}
// [_queue setMaxConcurrentOperationCount:2]; //设置并发操作个数
// [NSOperationQueue mainQueue]; //获取队列
[NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
NSLog(@"error on load = %@",[connectionError localizedDescription]);
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode != 200) {
NSLog(@"code = %@",[NSNumber numberWithInteger:httpResponse.statusCode]);
return ;
}
}
NSString *xml = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",xml);
}];
}
//TODO: 异步请求
- (void)startRequestWithURLString:(NSString *)urlString
{
_url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:_url];
_connection = [NSURLConnection connectionWithRequest:request delegate:self];
[_connection start];
}
#pragma mark - Connection detegate
//TODO: NSURLConnectionDataDelegate
// 链接收到HTTP重定向响应时得到调用
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
NSLog(@"[ Redirect request for %@ redirection to %@ ]",_url,request.URL);
NSLog(@"[ All headers = %@ ]",[(NSHTTPURLResponse *)response allHeaderFields]);
return request;
}
// 服务器接收到请求时
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"all headers = %@",[httpResponse allHeaderFields]);
if (httpResponse.statusCode != 200) {
NSLog(@"code is not 200 .");
[_connection cancel];
return;
}
}
//当收到服务器返回的数据时触发, 返回的可能是资源片段
static NSUInteger _totalDownload = 0;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
_totalDownload += [data length];
NSLog(@"received %lu ",(unsigned long)_totalDownload);
}
// 请求数据失败时触发
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%s load failed with error %@ ", __FUNCTION__,[error localizedDescription]);
}
//当服务器返回所有数据时触发, 数据返回完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"did finish loading .");
}
@end