iOS開發實踐之GET和POST請求

來源:互聯網
上載者:User

iOS開發實踐之GET和POST請求

GET和POST請求是HTTP請求方式中最最為常見的。在說請求方式之前先熟悉HTTP的通訊過程:

請求

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

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

2、要求標頭 : 用戶端的一些描述資訊

Host: 192.168.1.111:8080 // 用戶端想訪問的伺服器主機地址

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9) Firefox/30.0 // 用戶端的類型,用戶端的軟體環境

Accept: text/html, // 用戶端所能接收的資料類型

Accept-Language: zh-cn // 用戶端的語言環境

Accept-Encoding: gzip // 用戶端支援的資料壓縮格式

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

請求參數,發給伺服器的資料

響應

1、狀態行(響應行): HTTP協議的版本、響應狀態代碼、響應狀態原因

Server: Apache-Coyote/1.1 // 伺服器的類型

Content-Type: image/jpeg // 返回資料的類型

Content-Length: 56811 // 返回資料的長度

Date: Mon, 23 Jun 2014 12:54:52 GMT // 響應的時間

2、回應標頭:伺服器的一些描述資訊

Content-Type : 伺服器返回給用戶端的內容類型

Content-Length : 伺服器返回給用戶端的內容的長度(比如檔案的大小)

3、實體內容(響應體)

伺服器返回給用戶端具體的資料,比如檔案資料

NSMutableURLRequest(注意:非NSURLRequest因為這個對象是不可變的)

1、設定逾時時間(預設60s)

request.timeoutInterval = 15;

2、佈建要求方式

request.HTTPMethod = @"POST";

3、佈建要求體

request.HTTPBody = data;

4、佈建要求頭 例如如下是傳JSON資料的表頭設定

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

GET和POST對比:

GET(預設情況是get請求):

特點:GET方式提交的參數直接拼接到url請求地址中,多個參數用&隔開。例如:http://localhost:8080/myService/login?username=123&pwd=123

缺點:

1、在url中暴露了所有的請求資料,不太安全

2、由於瀏覽器和伺服器對URL長度有限制,因此在URL後面附帶的參數是有限制的,通常不能超過1KB

- (IBAction)login {    NSString *loginUser = self.userName.text;    NSString *loginPwd = self.pwd.text;    if (loginUser.length==0) {        [MBProgressHUD showError:@"請輸入使用者名稱!"];        return;    }        if (loginPwd.length==0) {        [MBProgressHUD showError:@"請輸入密碼!"];        return;    }         // 增加蒙板    [MBProgressHUD showMessage:@"正在登入中....."];           //預設是get方式請求:get方式參數直接拼接到url中    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/myService/login?username=%@&pwd=%@",loginUser,loginPwd];        //post方式請求,參數放在請求體中    //NSString *urlStr = @"http://localhost:8080/myService/login";        //URL轉碼    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];         //urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];        NSURL *url = [NSURL URLWithString:urlStr];        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];        //設定逾時時間(預設60s)    request.timeoutInterval = 15;        //佈建要求方式    request.HTTPMethod = @"POST";        //佈建要求體    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", loginUser,loginPwd];    // NSString --> NSData    request.HTTPBody =  [param dataUsingEncoding:NSUTF8StringEncoding];         // 佈建要求頭資訊    [request setValue:@"iphone" forHTTPHeaderField:@"User-Agent"];        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        //隱藏蒙板        [MBProgressHUD hideHUD];        if(connectionError || data==nil){            [MBProgressHUD showError:@"網路繁忙!稍後再試!"];            return ;        }else{           NSDictionary *dict =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];            NSString *error =  dict[@"error"];            if (error) {                [MBProgressHUD showError:error];            }else{                NSString *success = dict[@"success"];                [MBProgressHUD showSuccess:success];            }        }    }];        }

POST

特點:

1、把所有請求參數放在請求體(HTTPBody)中

2、理論上講,發給伺服器的資料的大小是沒有限制

3、請求資料相對安全(沒有絕對的安全)

 // 1.URL    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/myService/order"];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];        request.timeoutInterval = 15;    request.HTTPMethod = @"POST";        NSDictionary *orderInfo = @{                                @"shop_id" : @"1111",                                @"shop_name" : @"的地方地方",                                @"user_id" : @"8919"                                };    NSData *json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];    request.HTTPBody = json;        // 5.佈建要求頭:這次請求體的資料不再是普通的參數,而是一個JSON資料    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        if(connectionError || data==nil){            [MBProgressHUD showError:@"網路繁忙!稍後再試!"];            return ;        }else{            NSDictionary *dict =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];            NSString *error =  dict[@"error"];            if (error) {                [MBProgressHUD showError:error];            }else{                NSString *success = dict[@"success"];                [MBProgressHUD showSuccess:success];            }        }    }];

url轉碼問題(URL中不能包含中文)

1、這方法已淘汰

NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login?username=喝喝&pwd=123"];urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
2、官方推薦使用:
NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login?username=喝喝&pwd=123"];    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.