IOS NSURLRequest(http請求)講解 ---------贖罪之路


前言

     很久沒有寫過博客了,今天終於可以抽空寫。公司的項目從2016年03月15日(我第二份工作任職)開始,辛苦了3個多月終於接近尾聲了,在這當中我學了非常多東西,為了遺忘我就寫個博客來記錄下,以防止忘記。

正文  

     今天要講的主角是NSURLRequest。這里我先采用apple 官方文檔解釋

NSURLRequest objects represent a URL load request in a manner independent of protocol and URL scheme,

NSURLRequest encapsulates two basic data elements of a load request: the URL to load, and the policy to use when consulting the URL content cache made available by the implementation.

NSURLRequest is designed to be extended to support additional protocols by adding categories that provide accessor methods for your own protocol-specific properties. Those methods can get and set the actual values by calling the NSURLProtocol methods propertyForKey:inRequest: and setProperty:forKey:inRequest:.

以上引用蘋果官方解釋,大概就是NSURLRequest 是一個獨立的獨立加載請求的協議和解決方案,它封裝了 load URL 和 the policy,當你發送了網絡請求時候可以使用緩存,你可以通過它 propertyForKey:inRequest: 和 setProperty:forKey:inRequest:.這兩個方法添加你的協議,英語筆記差,翻譯不正確請指出。

 

   其實蘋果說了這多,說白就是這個是可以讓你發送網絡請求,你可以為這個類添加緩存,使得相同的URL不必在進行一次網絡請求,緩存到后面我們慢慢再談論,因為今天的主角是NSURLRequest。

 

例子一

    //1 需要請求的URL

    NSString *imageUrl = @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1467208812&di=3b6365a0a40959e9b1f9432372bc1ee3&src=http://img5.duitang.com/uploads/item/201208/13/20120813000951_iF2K4.thumb.700_0.jpeg";

    

    //2 NSString 封裝成 NSURL

    NSURL *url = [NSURL URLWithString:imageUrl];

    

    //3 定義NSURLRequest 對象

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    

    //4 發送請求

    

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        

        if(!connectionError){

            

            NSLog(@"加載成功");

            

            dispatch_async(dispatch_get_main_queue(), ^{

                

                //加載Image

                

                UIImage *image = [UIImage imageWithData:data];

                

                //顯示到UIImageView

                self.imageView.image = image;

            });

            

        }

        else

            NSLog(@"加載失敗");

    }];

第一個例子非常簡單,主要是引入門。大家可能會奇怪,為什么我沒有設置請求的類型(get 或者 post),因為NSURLReqest 默認是GET請求,所以我才沒有設置而沒有提示錯誤。

例子二(post請求)

    // 1 需要請求的URL String
    NSString *urlString = @"http://fmonline.server.kugou.net:8080/get_online";
    
    // 2 封裝成NSURL
    NSURL *url          = [NSURL URLWithString:urlString];
    
    // 3 定義NSURLRquest
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];//注意這個是mutable,說明這個是可變的
    
    // 4設置對應的屬性
    
    // 設置請求類型
    request.HTTPMethod   = @"post";//默認是 get

      //添加url

        request.URL          = url;

    //設置body內容
    NSString *bodyString = @"¼r¹}9:";
    NSData   *bodyData   = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody     = bodyData;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
    }];

   post請求一般都是采用NSMutableURLRequest 進行網絡請求,因為post請求一般包括 body 參數 或者 head。

 

簡單的兩個例子初步學習IOS 如何進行網絡請求

 

重點

在ios 9 即(xcode7)需要在info.plist

<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAppTransportSecurity</key>
<true/>

因為 iOS 9 就停用了http請求,默認采用https,但是目前沒有多少公司采用了https請求,因為要多支出費用。

結言

NSURLRequest 目前暫時先講到這里,下次我們來講NSURLConnect。

demo 下載地址 https://github.com/YeYanHong/NSURLReqest-Demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM