[iOS]-POST和GET网络请求

介绍POST和GET网络请求

GET是向服务器发索取数据的一种请求,而POST是向服务器提交数据并获取某些数据的一种请求。
在使用POST网络请求时,我们需要按照服务器端所需要接受的数据格式编写对应的body体代码

POST网络请求

		NSString *stringPhoneApi = @"http://116.62.180.44:8080/login";
        //stringPhoneApi = [stringPhoneApi stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *urlString = [NSURL URLWithString:stringPhoneApi];
        NSMutableURLRequest *requestTest = [NSMutableURLRequest requestWithURL:urlString];

        //requestTest.HTTPMethod = @"POST";
        [requestTest setHTTPMethod:@"POST"];
        
        //设置网络请求的请求体(请求体为json类型的字符串)
        //下方为将普通字符串转换为json类型的字符串
        NSNumber *codeTest = [NSNumber numberWithInt:0];
        NSDictionary *dict = @{@"code":codeTest, @"username":_myView.accountTextField.text, @"password":_myView.passwordTextField.text};
        
        NSData *dictPhoneData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
    //    NSLog(@"%@", dictPhoneData);
        NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:dictPhoneData options:0 error:nil]);
        //设置请求体body
        requestTest.HTTPBody = dictPhoneData;
        //设置请求头,这个很重要,一定要按照服务器接口的需求设置对应的请求头
        [requestTest addValue:@"application/json;UTF-8" forHTTPHeaderField:@"Content-Type"];
        
        NSURLSession *sessionTest = [NSURLSession sharedSession];
        
        NSURLSessionDataTask *testDataTask = [sessionTest dataTaskWithRequest:requestTest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (error == nil) {
                NSLog(@"请求成功");
            } else {
                NSLog(@"网络请求失败!");
            }
        }];
        //启动任务
        [testDataTask resume];

以上就是一个POST网络请求的全部流程了,我们需要注意的点如下:

  1. 请求需要写成NSMutableURLRequest *而不是NSURLRequest *
  2. 需要给请求设置请求方式为POST:[requestTest setHTTPMethod:@"POST"];
  3. 请求体body中的数据需要将所需数据(字典或字符串)转换为json类型的NSData *类型,如:NSData *dictPhoneData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
  4. 设置请求体:requestTest.HTTPBody = dictPhoneData;
  5. 非常重要的一步,根据实际需求设置请求头:[requestTest addValue:@"application/json;UTF-8" forHTTPHeaderField:@"Content-Type"];

GET网络请求

    //请求 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];
    //或者写为如下形式
	//NSMutableURLRequest *requestSecond = [NSMutableURLRequest initWithURL:url];
	//[requestSecond setHTTPMethod:@"GET"];
	
    //发送请求  默认为 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]);
        } else {
			NSLog(@"网络请求失败!");
		}
    }];
    //执行任务
    [dataTask resume];

GET请求的形式很简单,由于我们在不设置请求方式为POST或不设置请求方式的时候,默认的请求方式就是GET,所以我们只需要写好请求:NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];就好了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值