iOS中的HTTP請求處理

IOS中的HTTP請求處理

一、HTTP協議

1、定義

HTTP的全稱:超文本傳輸協議,用來定製傳輸數據的規範(客戶端和服務器之間的數據傳輸規範)

HTTP完整通信過程:請求行、請求頭、請求體

二、通信過程

1、請求(客戶端到服務端)

狀態行

請求頭(描述客戶端信息)

請求體(POST請求才有,存放具體數據)

2、響應(服務端到客戶端)

狀態行(響應行:HTTP協議版本\狀態碼\狀態信息)

響應頭(服務器信息\返回數據類型\返回數據長度)

實體內容(響應體,返回給客戶端的具體內容)

三、HTTP請求類型

1GET

  • 參數拼接在URL後面
  • 參數有限制

2POST

  • 參數都在請求體
  • 參數沒有限制
  • 文件上傳只能用POST

3HEAD

  • 獲得響應頭信息,不獲取響應體
  • request.HTTPMethod = @"HEAD";

4Delete

四、IOS中發送GET\POST的方式

1NSURLConnection

  • 蘋果原生
  • 使用起來比ASI\AFN複雜

2ASI

  • 基於CFNetwork
  • 提供了非常多強大的功能,使用簡單

3AFN

  • 基於NSURLConnection
  • 提供了常用的功能(無法監聽進度)


五、NSURLConnection

1、發送同步請求

//響應對象
    NSURLResponse *response = nil;
    //錯誤類
    NSError *error = nil;
    //發送同步請求
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

2、發送異步請求(block

//請求對象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"URLString"]];
    //異步請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
    }];

3、發送異步請求(delegate

//第一種
    [NSURLConnection connectionWithRequest:request delegate:self];
    //第二種
    [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    //第三種
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [connection start];

4、文件下載(大文件下載)

方案:邊下載邊寫入(寫到沙盒的某個文件中)

具體實現:

a.在接收到服務器的響應時,創建一個空文件

NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createFileAtPath:@"文件路徑" contents:nil attributes:nil];

b.創建一個跟空文件相關聯的句柄對象

NSFileHandle *writeHandler = [NSFileHandle fileHandleForReadingAtPath:@"文件路徑"];

c.在接收到服務器數據時,利用句柄對象將服務器返回的數據寫入

//移動到尾部
    [self.writeHandler seekToEndOfFile];
    //從當前爲開始寫
    [self.writeHandler writeData:data];

d.在接受完數據後,關閉句柄

//關閉句柄
    [self.writeHandler closeFile];
    self.writeHandler = nil;

5、斷點下載

設置請求頭的Range,告訴服務器下載哪一段數據

NSString *values = [NSString stringWithFormat:@"bytes=%lld-%lld",self.begin + self.currentLength, self.end];
    
    [request setValue:value forHTTPHeaderField:@"Range"];

6、文件上傳

只能用POST請求,請求參數都在請求體中(文件參數\非文件類型的參數)

a.拼接請求體(文件參數)

#define HMEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
    NSMutableData *body  = [NSMutableData data];
    //參數開始標記
    [body appendData:HMEncode(@"--heima\r\n")];
    //參數描述
    [body appendData:HMEncode(@"Content-Disposition: form-data; name=\"file\"; filename=\"20140519_27.png\"\r\n")];
    // 文件類型:Content-Type
    [body appendData:HMEncode(@"Content-Type: image/png\r\n")];
    //\r\n文件二進制數據\r\n
    [body appendData:HMEncode(@"\r\n")];
    NSData *fileData = UIImagePNGRepresentation(image);
    [body appendData:fileData];
    [body appendData:HMEncode(@"\r\n")];
    //結束
    [body appendData:HMEncode(@"--heima--\r\n")];
    request.HTTPBody = body;

b.設置請求頭

請求數據長度:

[request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];


請求數據類型Content-Type:

普通的post請求:application/x-www-form-urlencoded
上傳文件的post請求:multipart/form-data;boundary=boundary

六、NSURLCache緩存

獲取全局緩存對象

NSURLCache *cache = [NSURLCache sharedURLCache];

設置緩存容量

cache.memoryCapacity = 1024 * 1024;
cache.diskCapacity = 20 * 1024 * 1024;

設置請求的緩存策略

request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

/**

 *  AuthorJn

 *  GitHubhttps://github.com/JnKindle

 *  cnblogshttp://www.cnblogs.com/JnKindle

 *  QQ1294405741

 */





發佈了59 篇原創文章 · 獲贊 17 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章