網(wǎng)絡(luò)請求NSURLConnection筆記

發(fā)送異步請求

-(void)async
{

// 0.請求路徑
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
// 1.創(chuàng)建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.發(fā)送請求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    // 請求完畢會來到這個block
    // 3.解析服務(wù)器返回的數(shù)據(jù)(解析成字符串)
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", string);
}];

}

發(fā)送同步請求

-(void)sync
{

// 0.請求路徑
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
  // 1.創(chuàng)建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.發(fā)送請求
// sendSynchronousRequest阻塞式的方法,等待服務(wù)器返回數(shù)據(jù)
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// 3.解析服務(wù)器返回的數(shù)據(jù)(解析成字符串)
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 () <NSURLConnectionDataDelegate>
//輸出流對象
@property (nonatomic, strong) NSOutputStream *stream;
//用來存放服務(wù)器返回的數(shù)據(jù)
@property (nonatomic, strong) NSMutableData *responseData;
//文件的總長度
@property (nonatomic, assign) NSInteger contentLength;
//當(dāng)前下載的總長度
@property (nonatomic, assign) NSInteger currentLength;
//文件句柄對象
@property (nonatomic, strong) NSFileHandle *handle;
@end

  • 設(shè)置請求和代理
    -(void)delegateAysnc
    {
// 0.請求路徑
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
// 1.創(chuàng)建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/*
//2.創(chuàng)建連接對象
[[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];
    // 決定代理方法在哪個隊列中執(zhí)行
    [conn setDelegateQueue:[[NSOperationQueue alloc] init]];
    // 啟動子線程的runLoop
    self.runLoop = CFRunLoopGetCurrent();
    // 啟動runLoop
    CFRunLoopRun();
    // connectionDidFinishLoading方法停止RunLoop
    CFRunLoopStop(self.runLoop);
});

}

  • 接收到服務(wù)器的響應(yīng)
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
// 創(chuàng)建data對象
self.responseData = [NSMutableData data];
NSLog(@"didReceiveResponse");
/** -------------------------------下面是下載大文件------------------------------- **/
if (0) {
    // 獲得文件的總長度
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
    // 創(chuàng)建一個空的文件
    [[NSFileManager defaultManager] createFileAtPath:FilePath contents:nil attributes:nil];
    // 創(chuàng)建文件句柄
    self.handle = [NSFileHandle fileHandleForWritingAtPath:FilePath];
} else {//NSOutputStream下載大文件
    // response.suggestedFilename : 服務(wù)器那邊的文件名
    // 文件路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
    // 利用NSOutputStream往Path中寫入數(shù)據(jù)(append為YES的話,每次寫入都是追加到文件尾部)
    self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
    // 打開流(如果文件不存在,會自動創(chuàng)建)
    [self.stream open];
}

}

  • 接收到服務(wù)器的數(shù)據(jù)(如果數(shù)據(jù)量比較大,這個方法會被調(diào)用多次)
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
// 不斷拼接服務(wù)器返回的數(shù)據(jù)(小文件)
[self.responseData appendData:data];
NSLog(@"didReceiveData -- %zd", data.length);
/**-------------------------------下載大文件-------------------------------**/
if (0) {
    // 指定數(shù)據(jù)的寫入位置 -- 文件內(nèi)容的最后面
    [self.handle seekToEndOfFile];
    // 寫入數(shù)據(jù)
    [self.handle writeData:data];
    // 拼接總長度
    self.currentLength += data.length;
} else {//NSOutputStream下載大文件
         [self.stream write:[data bytes] maxLength:data.length];//拼接數(shù)據(jù)
         }

}

  • 服務(wù)器的數(shù)據(jù)成功接收完畢
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
NSString *string = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
//---------上面是轉(zhuǎn)字符串-----下面下載小文件-------------------------------
// 緩存文件夾
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 文件路徑
NSString *file = [caches stringByAppendingPathComponent:@"minion_15.mp4"];
// 寫入數(shù)據(jù)
[self.fileData writeToFile:file atomically:YES];
self.responseData = nil;
/**-------------------------------下載大文件-------------------------------**/
if (0) {
    // 關(guān)閉handle
    [self.handle closeFile];
    self.handle = nil;
    // 清空長度
    self.currentLength = 0;
} else{//關(guān)閉數(shù)據(jù)流
          [self.stream close];
         }

}

  • 請求失?。ū热缯埱蟪瑫r)
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
NSLog(@"didFailWithError -- %@", error);

}

post請求

-(void)postConnection{

// 1.請求路徑
NSString *urlStr = @"http://www.baidu.com/login?username=登陸&pwd=";
// 將中文URL進行轉(zhuǎn)碼
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
// 2.創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 更改請求方法
request.HTTPMethod = @"POST";
// 設(shè)置請求體
request.HTTPBody = [@"username=&pwd=" dataUsingEncoding:NSUTF8StringEncoding];
// 設(shè)置超時(5秒后超時)
request.timeoutInterval = 5;
// 設(shè)置請求頭
//    [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
// 3.發(fā)送請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (connectionError) { // 比如請求超時
        NSLog(@"----請求失敗");
    } else {
        NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
}];

} ////

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容