NSURLConnection
常用类
NSURL:请求地址
- NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有
- 一个NSURL对象
- 请求方法、请求头、请求体
- 请求超时 … …
NSMutableURLRequest:NSURLRequest的子类
NSURLConnection
- 负责发送请求,建立客户端和服务器的连接
- 发送数据给服务器,并收集来自服务器的响应数据
NSURLConnection的使用步骤
- 使用NSURLConnection发送请求的步骤很简单
- 创建一个NSURL对象,设置请求路径
- 传入NSURL创建一个NSURLRequest对象,设置请求头和请求体
- 使用NSURLConnection发送请求
NSURLConnection发送请求
- NSURLConnection常见的发送请求方法有以下几种
- 同步请求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
- 异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
- block回调
+ (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
- 代理
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
- 在startImmediately = NO的情况下,需要调用start方法开始发送请求
(void)start;
- 成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议
NSURLConnectionDelegate
- NSURLConnectionDataDelegate协议中的代理方法
- 开始接收到服务器的响应时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- 接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次)
-
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- 服务器返回的数据完全接收完毕后调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- 请求出错时调用(比如请求超时)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
NSMutableURLRequest
- NSMutableURLRequest是NSURLRequest的子类,常用方法有 设置请求超时等待时间(超过这个时间就算超时,请求失败)
- (void)setTimeoutInterval:(NSTimeInterval)seconds;
- 设置请求方法(比如GET和POST)
- (void)setHTTPMethod:(NSString *)method;
- 设置请求体
- (void)setHTTPBody:(NSData *)data;
设置请求头
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
创建GET和POST请求
- 创建GET请求
NSString *urlStr = [@"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
- 创建POST请求
NSString *urlStr = @"http://120.25.226.186:32812/login";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 请求体
NSString *bodyStr = @"username=520it&pwd=520it";
request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
多值参数
- 有时候一个参数名,可能会对应多个值 http://120.25.226.186:32812/weather?place=Beijing&place=Henan&place=Hunan
- 服务器的place属性是一个数组
使用
小文件下载
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
//获取文件的总长度
self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
self.fileData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.fileData appendData:data];
CGFloat progress = 1.0 * self.fileData.length / self.contentLength;
NSLog(@"已下载:%.2f%%", (progress) * 100);
self.progressView.progress = progress;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"下载完毕");
// 将文件写入沙盒中
// 缓存文件夹
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 文件路径
NSString *file = [caches stringByAppendingPathComponent:@"minion_15.mp4"];
// 写入数据
[self.fileData writeToFile:file atomically:YES];
self.fileData = nil;
}
大文件下载
#pragma mark - <NSURLConnectionDataDelegate>
/**
* 接收到响应的时候:创建一个空的文件
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
// 获得文件的总长度
self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
// 创建一个空的文件
[[NSFileManager defaultManager] createFileAtPath:XMGFile contents:nil attributes:nil];
// 创建文件句柄
self.handle = [NSFileHandle fileHandleForWritingAtPath:XMGFile];
}
/**
* 接收到具体数据:马上把数据写入一开始创建好的文件
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 指定数据的写入位置 -- 文件内容的最后面
[self.handle seekToEndOfFile];
// 写入数据
[self.handle writeData:data];
// 拼接总长度
self.currentLength += data.length;
// 进度
self.progressView.progress = 1.0 * self.currentLength / self.contentLength;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 关闭handle
[self.handle closeFile];
self.handle = nil;
// 清空长度
self.currentLength = 0;
}
文件上传
#define XMGBoundary @"520it"
#define XMGEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
#define XMGNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
- (void)viewDidLoad {
[super viewDidLoad];
// 创建请求
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 设置请求头(告诉告诉服务器,这是一个文件上传的请求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];
// 设置请求体
NSMutableData *body = [NSMutableData data];
// 文件参数
/*
--分割线\r\n
Content-Disposition: form-data; name="参数名"; filename="文件名"\r\n
Content-Type: 文件的MIMEType\r\n
\r\n
文件数据
\r\n
*/
// 分割线
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];
// 文件参数名
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:XMGNewLine];
// 文件的类型
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
[body appendData:XMGNewLine];
// 文件数据
[body appendData:XMGNewLine];
// UIImageJPEGRepresentation(<#UIImage *image#>, <#CGFloat compressionQuality#>)
UIImage *image = [UIImage imageNamed:@"placeholder"];
[body appendData:UIImagePNGRepresentation(image)];
// [body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:XMGNewLine];
// 非文件参数
/*
--分割线\r\n
Content-Disposition: form-data; name="参数名"\r\n
\r\n
参数值
\r\n
*/
// 分割线
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];
// 参数名
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\""])];
[body appendData:XMGNewLine];
// 参数值
[body appendData:XMGNewLine];
[body appendData:XMGEncode(@"jack")];
[body appendData:XMGNewLine];
// 结束标记
/*
--分割线--\r\n
*/
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGEncode(@"--")];
[body appendData:XMGNewLine];
request.HTTPBody = body;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
}
- NSOutputStream
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
/** 输出流对象 */
@property (nonatomic, strong) NSOutputStream *stream;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]] delegate:self];
}
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// response.suggestedFilename : 服务器那边的文件名
// 文件路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"%@", file);
// 利用NSOutputStream往Path中写入数据(append为YES的话,每次写入都是追加到文件尾部)
self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
// 打开流(如果文件不存在,会自动创建)
[self.stream open];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.stream write:[data bytes] maxLength:data.length];
NSLog(@"didReceiveData-------");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self.stream close];
NSLog(@"-------");
}
@end
NSURLConnection与RunLoop
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"]] delegate:self];
// 决定代理方法在哪个队列中执行
[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
// 子线程的RunLoop默认是不启动的,NSConnection在子线程发送请求,不会调用代理方法,除非启动子线程的runLoop
// 启动子线程的runLoop
// [[NSRunLoop currentRunLoop] run];
self.runLoop = CFRunLoopGetCurrent();
// 启动runLoop
CFRunLoopRun();
});