网络请求NSURLConnection笔记

发送异步请求

-(void)async
{

// 0.请求路径
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
// 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    // 请求完毕会来到这个block
    // 3.解析服务器返回的数据(解析成字符串)
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", string);
}];

}

发送同步请求

-(void)sync
{

// 0.请求路径
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
  // 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.发送请求
// sendSynchronousRequest阻塞式的方法,等待服务器返回数据
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// 3.解析服务器返回的数据(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@ %@", string, response.allHeaderFields);

}

NSURLConnection下载代理

#define FilePath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"1.zip"]
@interface ViewController ()
//输出流对象
@property (nonatomic, strong) NSOutputStream *stream;
//用来存放服务器返回的数据
@property (nonatomic, strong) NSMutableData *responseData;
//文件的总长度
@property (nonatomic, assign) NSInteger contentLength;
//当前下载的总长度
@property (nonatomic, assign) NSInteger currentLength;
//文件句柄对象
@property (nonatomic, strong) NSFileHandle *handle;
@end

  • 设置请求和代理
    -(void)delegateAysnc
    {
// 0.请求路径
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
// 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/*
//2.创建连接对象
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn start];
 //取消
[conn cancel];
 */
[NSURLConnection connectionWithRequest:request delegate:self];

--------------------下面是在子线程启动------------------------

dispatch_async(dispatch_get_global_queue(0, 0), ^{
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]] delegate:self];
    // 决定代理方法在哪个队列中执行
    [conn setDelegateQueue:[[NSOperationQueue alloc] init]];
    // 启动子线程的runLoop
    self.runLoop = CFRunLoopGetCurrent();
    // 启动runLoop
    CFRunLoopRun();
    // connectionDidFinishLoading方法停止RunLoop
    CFRunLoopStop(self.runLoop);
});

}

  • 接收到服务器的响应
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
// 创建data对象
self.responseData = [NSMutableData data];
NSLog(@"didReceiveResponse");
/** -------------------------------下面是下载大文件------------------------------- **/
if (0) {
    // 获得文件的总长度
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
    // 创建一个空的文件
    [[NSFileManager defaultManager] createFileAtPath:FilePath contents:nil attributes:nil];
    // 创建文件句柄
    self.handle = [NSFileHandle fileHandleForWritingAtPath:FilePath];
} else {//NSOutputStream下载大文件
    // response.suggestedFilename : 服务器那边的文件名
    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
    // 利用NSOutputStream往Path中写入数据(append为YES的话,每次写入都是追加到文件尾部)
    self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
    // 打开流(如果文件不存在,会自动创建)
    [self.stream open];
}

}

  • 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次)
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
// 不断拼接服务器返回的数据(小文件)
[self.responseData appendData:data];
NSLog(@"didReceiveData -- %zd", data.length);
/**-------------------------------下载大文件-------------------------------**/
if (0) {
    // 指定数据的写入位置 -- 文件内容的最后面
    [self.handle seekToEndOfFile];
    // 写入数据
    [self.handle writeData:data];
    // 拼接总长度
    self.currentLength += data.length;
} else {//NSOutputStream下载大文件
         [self.stream write:[data bytes] maxLength:data.length];//拼接数据
         }

}

  • 服务器的数据成功接收完毕
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
NSString *string = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
//---------上面是转字符串-----下面下载小文件-------------------------------
// 缓存文件夹
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 文件路径
NSString *file = [caches stringByAppendingPathComponent:@"minion_15.mp4"];
// 写入数据
[self.fileData writeToFile:file atomically:YES];
self.responseData = nil;
/**-------------------------------下载大文件-------------------------------**/
if (0) {
    // 关闭handle
    [self.handle closeFile];
    self.handle = nil;
    // 清空长度
    self.currentLength = 0;
} else{//关闭数据流
          [self.stream close];
         }

}

  • 请求失败(比如请求超时)
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
NSLog(@"didFailWithError -- %@", error);

}

post请求

-(void)postConnection{

// 1.请求路径
NSString *urlStr = @"http://www.baidu.com/login?username=登陆&pwd=";
// 将中文URL进行转码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
// 2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 更改请求方法
request.HTTPMethod = @"POST";
// 设置请求体
request.HTTPBody = [@"username=&pwd=" dataUsingEncoding:NSUTF8StringEncoding];
// 设置超时(5秒后超时)
request.timeoutInterval = 5;
// 设置请求头
//    [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
// 3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (connectionError) { // 比如请求超时
        NSLog(@"----请求失败");
    } else {
        NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
}];

} ////

你可能感兴趣的:(网络请求NSURLConnection笔记)