ios開髮網絡篇—Get請求和Post請求 - 轉

来源:https://www.cnblogs.com/jiuyi/archive/2018/12/13/10114231.html
-Advertisement-
Play Games

簡單說明:建議提交用戶的隱私數據一定要使用Post請求 相對Post請求而言,Get請求的所有參數都直接暴露在URL中,請求的URL一般會記錄在伺服器的訪問日誌中,而伺服器的訪問日誌是黑客攻擊的重點對象之一 用戶的隱私數據如登錄密碼,銀行帳號等 示例代碼 ...


簡單說明:建議提交用戶的隱私數據一定要使用Post請求 
相對Post請求而言,Get請求的所有參數都直接暴露在URL中,請求的URL一般會記錄在伺服器的訪問日誌中,而伺服器的訪問日誌是黑客攻擊的重點對象之一 
用戶的隱私數據如登錄密碼,銀行帳號等

示例代碼

#define CURRENT_SCREEN_WIDTH     [UIScreen mainScreen].bounds.size.width
#define CURRENT_SCREEN_HEIGHT     ([UIScreen mainScreen].bounds.size.height - 64)
#define BUTTON_WIDTH     80
#define BUTTON_HEIGHT    40

@interface ViewController ()
//GET 請求
@property(nonatomic,strong) UIButton *getButton;
//POST 請求
@property(nonatomic,strong) UIButton *postButton;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _getButton = [[UIButton alloc] initWithFrame:CGRectMake(CURRENT_SCREEN_WIDTH/2 - BUTTON_WIDTH/2,
                                                             CURRENT_SCREEN_HEIGHT/2 - BUTTON_HEIGHT,
                                                             BUTTON_WIDTH,
                                                             BUTTON_HEIGHT)];
    [_getButton setTitle:@"GET 請求" forState:UIControlStateNormal];
    [_getButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_getButton addTarget:self
                    action:@selector(getClick)
          forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_getButton];
    
    _postButton = [[UIButton alloc] initWithFrame:CGRectMake(CURRENT_SCREEN_WIDTH/2 - BUTTON_WIDTH/2,
                                                             _getButton.frame.origin.y + _getButton.frame.size.height + 60,
                                                             BUTTON_WIDTH,
                                                             BUTTON_HEIGHT)];
    [_postButton setTitle:@"POST 請求" forState:UIControlStateNormal];
    [_postButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_postButton addTarget:self
                    action:@selector(postClick)
          forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_postButton];
}

/* get 請求 */
-(void)getClick{
    //請求 URL
    NSString* urlStr = [NSString stringWithFormat:@"https://m.che168.com/beijing/?pvareaid=%d",110100];
    //封裝成 NSURL
    NSURL* url = [NSURL URLWithString:urlStr];

    //初始化 請求對象
    NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
    //也可以這樣初始化對象
    //NSURLRequest* request = [NSURLRequest requestWithURL:url];
    
    //發送請求  預設為 GET 請求
    //1 、獲得會話對象
    NSURLSession *session = [NSURLSession sharedSession];
    // 2、第一個參數:請求對象
    //      第二個參數:completionHandler回調(請求完成【成功|失敗】的回調)
    //      data:響應體信息(期望的數據)
    //      response:響應頭信息,主要是對伺服器端的描述
    //      error:錯誤信息,如果請求失敗,則error有值
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(!error){
            NSLog(@"請求載入成功。。。");
            //說明:(此處返回的數據是JSON格式的,因此使用NSJSONSerialization進行反序列化處理)
            // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            //如果是字元串則直接取出
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"GET 請求返回的結果是:%@",[str substringToIndex: 300]);
        }
    }];
    //執行任務
    [dataTask resume];
    
    /* ------------ ios9 之前請求方法,之後改成 NSURLSession 請求  --------------
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(!connectionError){
            NSLog(@"載入成功。。。");
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"載入的內容是:%@",[str substringToIndex:200]);
        }else{
            NSLog(@"載入失敗");
        }
    }];
    */
}


/* POST 請求 */
-(void)postClick{
    NSString *urlStr = [NSString stringWithFormat:@"https://m.che168.com/"];
    //轉碼
    // stringByAddingPercentEscapesUsingEncoding 只對 `#%^{}[]|\"<> 加空格共14個字元編碼,不包括”&?”等符號), ios9將淘汰
    // ios9 以後要換成 stringByAddingPercentEncodingWithAllowedCharacters 這個方法進行轉碼
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"?!@#$^&%*+,:;='\"`<>()[]{}/\\| "] invertedSet]];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //創建會話對象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //創建請求對象
    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[@"a=1&b=2&c=3&type=json" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //根據會話對象創建一個 Task(發送請求)
    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(!error){
            //8.解析數據
            // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            // NSLog(@"%@",dict);
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"POST 載入的內容是:%@",[str substringToIndex:200]);
        }else{
            NSLog(@"請求發生錯誤:%@", [error description]);
        }
    }];
    [dataTask resume]; //執行任務
}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • hive中left/right join on連接中and與where的使用問題 ...
  • 1. Docker搭建Mongodb 1.1 獲取docker鏡像 1.2 創建mongodb容器 如果加需要驗證就加 auth,不需要驗證,就去掉。預設mongodb是不使用用戶認證 1.3 進入容器設置用戶 或者直接進入admin 1.4 測試 查看是否連接成功 2.維護mongoDB 2.1 ...
  • Adroid佈局 有人形象地比喻,Android開發中的佈局就相當於一棟建築的外觀架構。佈局用得好,這棟建築的外觀才美觀高大上。 Android佈局管理器 Android佈局管理器本身是一個界面控制項,所有的佈局管理器都是ViewGroup類的子類,都是可以當做容器類來使用的。因此一個佈局管理器中可以 ...
  • 轉載請標明出處,維權必究:https://www.cnblogs.com/tangZH/p/10116298.html 在項目過程中出現了上述錯誤。 會出現這樣的錯誤是在我使用: notifyItemRemoved(position); notifyItemRangeChanged(position ...
  • 轉載請標明出處,維權必究:https://www.cnblogs.com/tangZH/p/10116095.html 我們為了移除RecycleView的某一項,會用RecycleView的notifyItemRemoved(int position)方法,但是需要註意的是:1、用該方法之後並不會 ...
  • 一、思路 第一,圖片拖拽位置互換/刪除,參照第三方; 第二,圖片用scrollview瀏覽,縮放用zoomToRect,不用CGAffineTransformScale; 其次,還要返回當前縮放圖片 二、核心代碼就不貼了,HDragItemListView.m主要處理圖片拖拽的功能 三、效果圖 Gi ...
  • 導入項目時,發現之前項目的butter knife報錯,用到註解的應該都會報錯Error:Execution failed for task ':app:javaPreCompileDebug'.> Annotation processors must be explicitly declared ...
  • 說明: 1.該文主要介紹如何使用NSURLSession來發送GET請求和POST請求 2.本文將不再講解NSURLConnection的使用,如有需要瞭解NSURLConnection如何發送請求。 詳細信息,請參考:http://www.cnblogs.com/wendingding/p/381 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...