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]];



      
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值