iOS HTTP請求與解析

1 HTTP兩種請求方案

1),蘋果原生

NSURLConnect:經典簡單web

NSURLSession:iOS7新出,功能較強大算法

CFNetwork:NSURL*的底層,純C語言apache

2),第三方框架(建議使用,提升效率)

ASIHttpRequest:功能十分強大,但中止更新json

AFNetworking:主流,簡單易用,更新十分快數組

MKNetworkKit:簡單,但少用tomcat

2 HTTP的通訊過程

1).請求

1> 請求行 : 請求方法、請求路徑、HTTP協議的版本安全

GET /MJServer/resources/images/1.jpg HTTP/1.1

2> 請求頭 : 客戶端的一些描述信息
服務器

* User-Agent : 客戶端的環境(軟件環境)網絡

3> 請求體 : POST請求才有這個東西
session

* 請求參數,發給服務器的數據

2).響應

1> 狀態行(響應行): HTTP協議的版本、響應狀態碼、響應狀態描述

HTTP/1.1 200 OK

2> 響應頭:服務器的一些描述信息

* Content-Type : 服務器返回給客戶端的內容類型

* Content-Length : 服務器返回給客戶端的內容的長度(好比文件的大小)

3> 實體內容(響應體)

* 服務器返回給客戶端具體的數據,好比文件數據

3 移動端HTTP請求分析數據的步驟

1.拼接"請求URL" + "?" + "請求參數"

* 請求參數的格式:參數名=參數值
* 多個請求參數之間用&隔開:參數名1=參數值1&參數名2=參數值2
* 好比:http://localhost:8080/MJServer/login?username=123&pwd=456

2.發送請求

3.解析服務器返回的數據

3.1 iOS中發送HTTP請求方式

1).GET

1> 特色

* 全部請求參數都拼接在url後面

2> 缺點

* 在url中暴露了全部的請求數據,不太安全

* url的長度有限制,不能發送太多的參數

3> 使用場合

* 若是僅僅是向服務器索要數據,通常用GET請求

* 默認就是GET請求

4> 如何發送一個GET請求

// 1.URL
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
// 2.請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.發送請求(子線程發送)
[NSURLConnection sendAsynchronousRequest:request 
                                    queue:[NSOperationQueue mainQueue] 
                         ompletionHandler:^(NSURLResponse *response, 
                                                        NSData *data, 
                                                        NSError *connectionError) {
}];
    //發送一個同步請求(在主線程發送請求)
    NSData *data = [NSURLConnection sendSynchronousRequest:request 
                                                    returningResponse:nil error:nil];

2).POST

1> 特色

* 把全部請求參數放在請求體(HTTPBody)中

* 理論上講,發給服務器的數據的大小是沒有限制

2> 使用場合

* 除開向服務器索要數據之外的請求,均可以用POST請求

* 若是發給服務器的數據是一些隱私、敏感的數據,絕對要用POST請求

3> 如何發送一個POST請求

// 1.建立一個URL : 請求路徑
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"];
// 2.建立一個請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 設置請求方法
request.HTTPMethod = @"POST";
// 設置請求體 : 請求參數
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];
// NSString --> NSData
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
// 3.發送請求(子線程發送)
[NSURLConnection sendAsynchronousRequest:request 
                                    queue:[NSOperationQueue mainQueue] 
                         ompletionHandler:^(NSURLResponse *response, 
                                                        NSData *data, 
                                                        NSError *connectionError) {
}];
    //發送一個同步請求(在主線程發送請求)
    NSData *data = [NSURLConnection sendSynchronousRequest:request 
                                                    returningResponse:nil error:nil];

3.2 解析服務器返回的數據

1)JSON解析

1>特色

*JSON解析規律

* { } --> NSDictionary @{ }
* [ ] --> NSArray @[ ]
* " " --> NSString @" "
* 10 --> NSNumber @10

*數據量少,服務器經常使用返回的數據

  // 3.發送請求(子線程發送)
  * request : 須要發送的請求
  * queue : 通常用主隊列,存放handler這個任務
  * handler : 當請求完畢後,會自動調用這個block
[NSURLConnection sendAsynchronousRequest:request 
                                    queue:[NSOperationQueue mainQueue] 
                         ompletionHandler:^(NSURLResponse *response, 
                                                        NSData *data, 
                                                        NSError *connectionError) {
   // 解析服務器返回的JSON數據
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data 
                                           options:NSJSONReadingMutableLeaves 
                                           error:nil];
    NSString *error = dict[@"error"];
    if (error) return; 
     else {
        NSString *success = dict[@"success"];
    }
                                                        
}];

2)XML解析

1.語法

1> 文檔聲明

<?xml version="1.0" encoding="UTF-8" ?>

2> 元素

* videos和video是元素(節點)

* video元素是videos元素的子元素

3> 屬性

<videos>
    <video name="小黃人 第01部" length="10"/>
    <video name="小黃人 第01部" length="10"/>
</videos>

* name和length叫作元素的屬性

2.解析

1> SAX解析

*逐個元素往下解析,適合大文件

* NSXMLParser

[NSURLConnection sendAsynchronousRequest:request 
                                    queue:[NSOperationQueue mainQueue] 
                         ompletionHandler:^(NSURLResponse *response, 
                                                        NSData *data, 
                                                        NSError *connectionError) {
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"網絡繁忙,請稍後再試!"];
            return;
        }
        // 解析XML數據
        // 1.建立XML解析器 -- SAX -- 逐個元素往下解析
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
        // 2.設置代理 重要!
        parser.delegate = self;
        // 3.開始解析(同步執行)
        [parser parse];
        // 4.刷新表格
        [self.tableView reloadData];
    }];

/**
 *  解析到一個元素的開始就會調用
 *  @param elementName   元素名稱
 *  @param attributeDict 屬性字典
 */
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
                                        namespaceURI:(NSString *)namespaceURI 
                                       qualifiedName:(NSString *)qName 
                                          attributes:(NSDictionary *)attributeDict
{
    if ([@"videos" isEqualToString:elementName]) return;
    
    HMVideo *video = [HMVideo videoWithDict:attributeDict];
    [self.videos addObject:video];
}

// 解析到文檔的開頭時會調用
- (void)parserDidStartDocument:(NSXMLParser *)parser

/* 解析到一個元素的結束就會調用
 *   @param elementName   元素名稱
 */  
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
                                      namespaceURI:(NSString *)namespaceURI 
                                     qualifiedName:(NSString *)qName

// 解析到文檔的結尾時會調用(解析結束)
- (void)parserDidEndDocument:(NSXMLParser *)parser
2> DOM解析

*一口氣將整個XML文檔加載進內存,適合小文件,使用最簡單

* GDataXML的使用步驟:

    1>導入這個GDataXML文件

    2>添加libxml2.dylib這個動態庫

    3>在Bulid Settings的Header Search Paths 添加路徑  /usr/include/libxml2

    4>在Bulid Phases的Compile Sources 找到CDataXMLNode 添加 -fno-objc-arc,通知編譯器這是非arc

// 3.發送請求
[NSURLConnection sendAsynchronousRequest:request 
                                    queue:[NSOperationQueue mainQueue] 
                         ompletionHandler:^(NSURLResponse *response, 
                                                        NSData *data, 
                                                        NSError *connectionError) {
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"網絡繁忙,請稍後再試!"];
            return;
        }
        // 解析XML數據
        // 加載整個XML數據
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data 
                                                        options:0 error:nil];
       // 得到文檔的根元素 -- videos元素
        GDataXMLElement *root = doc.rootElement;
      // 得到根元素裏面的全部video元素
        NSArray *elements = [root elementsForName:@"video"];
      // 遍歷全部的video元素
        for (GDataXMLElement *videoElement in elements) {
            HMVideo *video = [[HMVideo alloc] init];
           / 取出元素的屬性
           video.id = [videoElement attributeForName:@"id"].stringValue.intValue;
           video.name = [videoElement attributeForName:@"name"].stringValue;
           video.image = [videoElement attributeForName:@"image"].stringValue;
           video.url = [videoElement attributeForName:@"url"].stringValue;
             // 添加到數組中
           [self.videos addObject:video];
        }
        // 刷新表格
        [self.tableView reloadData];
    }];

4 數據安全

4.1.網絡數據加密

1> 加密對象:隱私數據,好比密碼、銀行信息

2> 加密方案

* 提交隱私數據,必須用POST請求

* 使用加密算法對隱私數據進行加密,好比MD5

3> 加密加強:爲了加大破解的難度

* 對明文進行2次MD5 : MD5(MD5($pass))

* 先對明文撒鹽,再進行MD5 : MD5($pass.$salt) 撒鹽是添加一些干擾數據

* 先MD5加密,再打亂暗文順序

4.2.本地存儲加密

1> 加密對象:重要的數據,好比遊戲數據

4.3.代碼安全問題

1> 如今已經有工具和技術能反編譯出源代碼:逆向工程

* 反編譯出來的都是純C語言的,可讀性不高

* 最起碼能知道源代碼裏面用的是哪些框架

5 監測網絡狀態

5.1.主動監測監測網絡狀態

// 是否WIFI  類方法
+ (BOOL)isEnableWIFI {
    return ([[Reachability reachabilityForLocalWiFi] 
                    currentReachabilityStatus] != NotReachable);
}
// 是否3G
+ (BOOL)isEnable3G {
    return ([[Reachability reachabilityForInternetConnection] 
                    currentReachabilityStatus] != NotReachable);
}

5.2.使用通知監控網絡狀態

1>使用蘋果官方提供的 Reachability類

1> 監聽通知
[[NSNotificationCenter defaultCenter] addObserver:self 
                            selector:@selector(networkStateChange) 
                            name:kReachabilityChangedNotification object:nil];
2> 開始監聽網絡狀態
// 得到Reachability對象
self.reachability = [Reachability reachabilityForInternetConnection];
// 開始監控網絡
[self.reachability startNotifier];

5.3.移除監聽

- (void)delloc
{
    [self.reachability stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

6 iOS7:NSURLSession

1> NSURLSessionDataTask
* 用途:用於非文件下載的GET\POST請求
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];
NSURLSessionDataTask *task = [self.session dataTaskWithURL:url];
NSURLSessionDataTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
       }];

2> NSURLSessionDownloadTask
* 用途:用於文件下載(小文件、大文件)
NSURLSessionDownloadTask *task = [self.session downloadTaskWithRequest:request];
NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url];
NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    
}];

7 下載

6.1.小文件下載

* 直接使用NSData
* NSURLConnection發送異步請求的方法
1.block形式 - 除開大文件下載之外的操做,均可以用這種形式
//使用了block就不須要使用代理方法
[NSURLConnection sendAsynchronousRequest:<#(NSURLRequest *)#> queue:<#(NSOperationQueue *)#> completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
 }];

6.2.大文件下載(斷點下載)

1>利用NSURLConnection和它的代理方法
@property (nonatomic, strong) NSFileHandle *writeHandle;
@property (nonatomic, assign) long long totalLength;
@property (nonatomic, assign) long long currentLength;
@property (nonatomic, strong) NSURLConnection *conn;

1> 發送一個請求
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"];
// 2.請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.下載(建立完conn對象後,會自動發起一個異步請求)
//要遵照NSURLConnectionDataDelegate協議
[NSURLConnection connectionWithRequest:request delegate:self];

2>#pragma mark - NSURLConnectionDataDelegate代理方法 
在代理方法中處理服務器返回的數據
/**
 在接收到服務器的響應時:
 1.建立一個空的文件
 2.用一個句柄對象關聯這個空的文件,目的是:方便後面用句柄對象往文件後面寫數據
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 文件路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"];
    
    // 建立一個空的文件 到 沙盒中
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filepath contents:nil attributes:nil];
    
    // 建立一個用來寫數據的文件句柄
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
}

/**
 在接收到服務器返回的文件數據時,利用句柄對象往文件的最後面追加數據
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 移動到文件的最後面
    [self.writeHandle seekToEndOfFile];
    
    // 將數據寫入沙盒
    [self.writeHandle writeData:data];
}

/**
 在全部數據接收完畢時,關閉句柄對象
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 關閉文件
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

3,斷點下載
- (IBAction)download:(UIButton *)sender {
    // 狀態取反
    sender.selected = !sender.isSelected;
    if (sender.selected) { // 繼續(開始)下載
        // 1.URL
        NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"];
       // 2.請求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        // 設置請求頭
        NSString *range = [NSString stringWithFormat:@"bytes=%lld-", self.currentLength];
        [request setValue:range forHTTPHeaderField:@"Range"];
        
        // 3.下載(建立完conn對象後,會自動發起一個異步請求)
        self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
    } else { // 暫停
        [self.conn cancel];
        self.conn = nil;
    }
}
2>利用NSURLSession和它的代理方法
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session;
//遵照NSURLSessionDownloadDelegate代理協議
- (NSURLSession *)session
{
    if (!_session) {
        // 得到session
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

-(IBAction)download:(UIButton *)sender {
    // 按鈕狀態取反
    sender.selected = !sender.isSelected;
    
    if (self.task == nil) { // 開始(繼續)下載
        if (self.resumeData) { // 恢復
            [self resume];
        } else { // 開始
            [self start];
        }
    } else { // 暫停
        [self pause];
    }
}

//從零開始
- (void)start
{
    // 1.建立一個下載任務
    NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/MJServer/resources/videos/minion_01.mp4"];
    self.task = [self.session downloadTaskWithURL:url];
    
    // 2.開始任務
    [self.task resume];
}
//恢復(繼續)
- (void)resume
{
    // 傳入上次暫停下載返回的數據,就能夠恢復下載
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    
    // 開始任務
    [self.task resume];
    
    // 清空
    self.resumeData = nil;
}
//暫停
- (void)pause
{
    __weak typeof(self) vc = self;
    [self.task cancelByProducingResumeData:^(NSData *resumeData) {
        //  resumeData : 包含了繼續下載的開始位置\下載的url
        vc.resumeData = resumeData;
        vc.task = nil;
    }];
}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename : 建議使用的文件名,通常跟服務器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
   // 將臨時文件剪切或者複製Caches文件夾
    NSFileManager *mgr = [NSFileManager defaultManager];
   [mgr moveItemAtPath:location.path toPath:file error:nil];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"得到下載進度--%@", [NSThread currentThread]);
    // 得到下載進度
    self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    
}

8 上傳

1,文件上傳的步驟

1.設置請求頭
* 目的:告訴服務器請求體裏面的內容並不是普通的參數,而是包含了文件參數
[request setValue:@"multipart/form-data; boundary=標識" forHTTPHeaderField:@"Content-Type"];

2.設置請求體
* 做用:存放參數(文件參數和非文件參數)
1> 非文件參數
[body appendData:HMEncode(@"--標識\r\n")];
[body appendData:HMEncode(@"Content-Disposition: form-data; name=\"username\"\r\n")];

[body appendData:HMEncode(@"\r\n")];
[body appendData:HMEncode(@"張三")];
[body appendData:HMEncode(@"\r\n")];

2> 文件參數
[body appendData:HMEncode(@"--heima\r\n")];
[body appendData:HMEncode(@"Content-Disposition: form-data; name=\"file\"; filename=\"test123.png\"\r\n")];
[body appendData:HMEncode(@"Content-Type: image/png\r\n")];

[body appendData:HMEncode(@"\r\n")];
[body appendData:imageData];
[body appendData:HMEncode(@"\r\n")];

3> 結束標記 :參數結束的標記
[body appendData:HMEncode(@"--標識--\r\n")];

2,封裝好的實例

=========================================封裝好的實例=========================================
//filename要上傳的文件名字,mimeType文件類型,fileDate上傳的文件數據,一般是url獲取文件地址,params是含有多參數的鍵值對的字典
eg:1,fileDate
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"autolayout" withExtension:@"txt"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    2,params
        NSDictionary *params = @{
                             @"username" : @"李四",
                             @"pwd" : @"123",
                             @"age" : @30,
                             @"height" : @"1.55"
                             };
 
 
 
- (void)upload:(NSString *)filename mimeType:(NSString *)mimeType fileData:(NSData *)fileData params:(NSDictionary *)params
{
    // 1.請求路徑
    NSURL *url = [NSURL URLWithString:@"xxxxx"];
    
    // 2.建立一個POST請求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    // 3.設置請求體
    NSMutableData *body = [NSMutableData data];
    
    // 3.1.文件參數,具體參數格式可使用charles工具截取觀察。\r\n硬性換行
    //str轉換爲data
    #define HMEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
    #define HMNewLien @"\r\n"
    #define HMFileBoundary @"xxxxxxx"   標識
    
    [body appendData:HMEncode(@"--")];
    [body appendData:HMEncode(HMFileBoundary)];
    [body appendData:HMEncode(HMNewLien)];
    
    NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"", filename];
    [body appendData:HMEncode(disposition)];
    [body appendData:HMEncode(HMNewLien)];
    
    NSString *type = [NSString stringWithFormat:@"Content-Type: %@", mimeType];
    [body appendData:HMEncode(type)];
    [body appendData:HMEncode(HMNewLien)];
    
    [body appendData:HMEncode(HMNewLien)];
    [body appendData:fileData];
    [body appendData:HMEncode(HMNewLien)];
    
    // 3.2.非文件參數
    /* [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
     *遍歷parames這個字典的鍵值,有多少對,就自動遍歷多少次
     */
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [body appendData:HMEncode(@"--")];
        [body appendData:HMEncode(HMFileBoundary)];
        [body appendData:HMEncode(HMNewLien)];
        
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"", key];
        [body appendData:HMEncode(disposition)];
        [body appendData:HMEncode(HMNewLien)];
        
        [body appendData:HMEncode(HMNewLien)];
        [body appendData:HMEncode([obj description])];
        [body appendData:HMEncode(HMNewLien)];
    }];
    
    // 3.3.結束標記
    [body appendData:HMEncode(@"--")];
    [body appendData:HMEncode(HMFileBoundary)];
    [body appendData:HMEncode(@"--")];
    [body appendData:HMEncode(HMNewLien)];
    
    request.HTTPBody = body;
    
    // 4.設置請求頭(告訴服務器此次傳給你的是文件數據,告訴服務器如今發送的是一個文件上傳請求)
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", HMFileBoundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    // 5.發送請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@", dict);
    }];
}

ps:獲取文件類型的方法MIMEType

1.百度搜索

2.查找服務器下面的某個xml文件
apache-tomcat-6.0.41\conf\web.xml

3.加載文件時經過Reponse得到
- (NSString *)MIMEType:(NSURL *)url
{
    // 1.建立一個請求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 2.發送請求(返回響應)
    NSURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    // 3.得到MIMEType
    return response.MIMEType;
}

9,解壓縮

1、技術方案
1.第三方框架:SSZipArchive
2.依賴的動態庫:libz.dylib

2、壓縮1
1.第一個方法
/**
 zipFile :產生的zip文件的最終路徑
 directory : 須要進行的壓縮的文件夾路徑
 */
[SSZipArchive createZipFileAtPath:zipFile withContentsOfDirectory:directory];

2.第一個方法
/**
 zipFile :產生的zip文件的最終路徑
 files : 這是一個數組,數組裏面存放的是須要壓縮的文件的路徑的集合
 files = @[@"/Users/apple/Destop/1.png", @"/Users/apple/Destop/3.txt"]
 */
[SSZipArchive createZipFileAtPath:zipFile withFilesAtPaths:files];

3、解壓縮
/**
 zipFile :須要解壓的zip文件的路徑
 dest : 解壓到什麼地方
 */
[SSZipArchive unzipFileAtPath:zipFile toDestination:dest];


10 AFNetwork

*通常只用於下載小文件

1,發送請求

1、2大管理對象
1.AFHTTPRequestOperationManager
* 對NSURLConnection的封裝
2.AFHTTPSessionManager
* 對NSURLSession的封裝

2、AFHTTPRequestOperationManager的具體使用
1.建立管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
2.封裝請求參數
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"哈哈哈";
params[@"pwd"] = @"123";
3.發送請求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr POST/GET:url parameters:params
  success:^(AFHTTPRequestOperation *operation, id responseObject) {
      // 請求成功的時候調用這個block
      //responseObject 若是是json數據,就默認解析爲字典
      NSLog(@"請求成功---%@", responseObject);
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      // 請求失敗的時候調用調用這個block
      NSLog(@"請求失敗");
  }];
  
3、對服務器返回數據的解析
1.AFN能夠自動對服務器返回的數據進行解析
* 默認將服務器返回的數據當作JSON來解析
2.設置對服務器返回數據的解析方式
    1> 當作是JSON來解析(默認作法)
    * mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    * responseObject的類型是NSDictionary或者NSArray

    2> 當作是XML來解析
    * mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
    * responseObject的類型是NSXMLParser

    3> 直接返回data
    * 意思是:告訴AFN不要去解析服務器返回的數據,保持原來的data便可
    * mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
3.注意
* 服務器返回的數據必定要跟responseSerializer對得上

2,下載

   //AFNetwork的下載必須配合NSURLConnection或者NSURLSession才行
   
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];

11 ASI

*功能十分強大,但已中止更新

3,上傳

  //上傳和下載基本相同,都是發送請求,但發送請求的方法不同
  // 1.建立一個管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 2.封裝參數(這個字典只能放非文件參數)
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"username"] = @"123";
    
    // 3.發送一個請求
    NSString *url = @"http://192.168.15.172:8080/MJServer/upload";
    [mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
        [formData appendPartWithFileData:fileData name:@"file" fileName:@"haha.jpg" mimeType:@"image/jpeg"];

        // 不是用這個方法來設置文件參數
//        [formData appendPartWithFormData:fileData name:@"file"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"上傳成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"上傳失敗");
    }];

4,監控網絡狀態

 
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 當網絡狀態發生改變的時候調用這個block
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"自帶網絡");
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"沒有網絡");
                break;
                
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知網絡");
                break;
            default:
                break;
        }
    }];
    // 開始監控
    [mgr startMonitoring];

其餘:

1 NSMutableURLRequest的經常使用方法

1>.設置超時

request.timeoutInterval = 5;

* NSURLRequest是不能設置超時的,由於這個對象是不可變的

*NSMutableURLRequest並不表明就是post請求,也能夠是get請求。系統默認是get請求,使用這個,表明url可改

9、URL轉碼

1.URL中不能包含中文,得對中文進行轉碼(加上一堆的%)

NSString *urlStr = @"http://localhost/login?username=喝喝&pwd=123";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// urlStr == @"http://localhost/login?username=%E5%96%9D%E5%96%9D&pwd=123"
相關文章
相關標籤/搜索