iOS-发送GET和POST请求

一 . 说明:
iOS9.0之后 , 苹果推出了NSURLSession来取代NSURLConnection , 所以今天写一篇文章总结一下所学 . 总结前有两点说明 :
1 ) 今天主要是针对NSURLSession . 将不对NSURLConnection做任何讲解 .
2 ) 工程已经配置好了http请求相关 .

二 . GET请求
GET请求共有两种创建方法 , 针对Request的和针对URL的 .

//针对Request的
-(void)requestGet
 {
  //GET请求,直接把请求参数跟在URL的后面以?隔开 , 多个参数之间以&符号拼接
  举例:http://www.dronghui.com/drhxx?m=xxx&b=xxxx&n=xxx

  //1.确定请求路径
  NSURL *url = [NSURL URLWithString:@"http://www.dronghui.com"];
  
  //2.创建请求对象
  //请求对象内部默认已经包含了请求头和请求方法(GET)
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  
  //3.获得会话对象
  NSURLSession *session = [NSURLSession sharedSession];
    
  //4.根据会话对象创建一个Task ( 发送请求 )
  /*
   第一个参数 : 请求对象
   第二个参数 : completionHandler回调 ( 请求完成 ["成功"or"失败"] 的回调 )
             data : 响应体信息(期望的数据)
             response : 响应头信息,主要是对服务器端的描述
             error : 错误信息 , 如果请求失败 , 则error有值
   */
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
      
      if (error == nil) {
          //6.解析服务器返回的数据
          //说明:(此处返回的数据是JSON格式的,因此使用NSJSONSerialization进行反序列化处理)
          NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
          
          NSLog(@"%@",dict);
      }
   }];
   
   //5.执行任务
   [dataTask resume];
 }

//针对URL的
-(void)urlGet
{
  //1.确定请求路径
  NSURL *url = [NSURL URLWithString:@"http://www.dronghui.com"];

  //2.获得会话对象
  NSURLSession *session = [NSURLSession sharedSession];

  //3.根据会话对象创建一个Task(发送请求)
  /*
   第一个参数:请求路径
   第二个参数:completionHandler回调 ( 请求完成["成功"or"失败"]的回调 )
             data:响应体信息 ( 期望的数据 )
             response:响应头
             error:错误信息 , 请求失败 , error有值
   注意:
      1)该方法内部会自动将请求路径包装成一个请求对象 , 该请求对象默认包含了请求头信息和请求方法 ( GET )
      2)如果要发送的是POST请求 , 则不能使用该方法
   */
  NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    //5.解析数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"%@",dict);
    
}];

//4.执行任务
[dataTask resume];
}

三 . POST请求
基本与get一致 , request.HTTPMethod = @"POST"

-(void)post
{

//1.创建会话对象
NSURLSession *session = [NSURLSession sharedSession];
//2.根据会话对象创建task
NSURL *url = [NSURL URLWithString:@"http://image.baidu.com/search/detail"];

//3.创建可变的请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//4.修改请求方法为POST
request.HTTPMethod = @"POST";

//5.设置请求体
request.HTTPBody = [@"ct=503316480&z=0&ipn=false&word=刘亦菲&hs=0&pn=-1&spn=0&di=baikeimg&pi=&rn=1&tn=baiduimagedetail&is=&istype=&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=&ln=undefined&fr=ala&fmq=undefined&fm=undefined&ic=&s=&se=&sme=&tab=&width=&height=&face=&cg=star&bdtype=0&oriquery=&objurl=http%3A%2F%2Fimgsrc.baidu.com%2Fbaike%2Fpic%2Fitem%2Fe4dde71190ef76c604622df99816fdfaae5167b4.jpg&fromurl=http%3A%2F%2Fbaike.baidu.com%2Fsubview%2F3064%2F13233367.htm&gsm=" dataUsingEncoding:NSUTF8StringEncoding];

//6.根据会话对象创建一个Task(发送请求)
/*
 第一个参数:请求对象
 第二个参数:completionHandler回调(请求完成【成功|失败】的回调)
            data:响应体信息(期望的数据)
            response:响应头信息,主要是对服务器端的描述
            error:错误信息,如果请求失败,则error有值
 */
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    //8.解析数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"%@",dict);
    
  }];

  //7.执行任务
  [dataTask resume];
}

四 . 代理相关

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) NSMutableData *responseData;
@end

@implementation ViewController

-(NSMutableData *)responseData
{
    if (_responseData == nil) {
        _responseData = [NSMutableData data];
    }
    return _responseData;
}

//当点击控制器View的时候会调用该方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self delegateTest];
}

//发送请求,代理方法
-(void)delegateTest
{
    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

    //2.创建请求对象
    //请求对象内部默认已经包含了请求头和请求方法(GET)
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //3.获得会话对象,并设置代理
/*
 第一个参数:会话对象的配置信息defaultSessionConfiguration 表示默认配置
 第二个参数:谁成为代理,此处为控制器本身即self
 第三个参数:队列,该队列决定代理方法在哪个线程中调用,可以传主队列|非主队列
 [NSOperationQueue mainQueue]   主队列:   代理方法在主线程中调用
 [[NSOperationQueue alloc]init] 非主队列: 代理方法在子线程中调用
 */
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //4.根据会话对象创建一个Task(发送请求)
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];

    //5.执行任务
    [dataTask resume];
}

//1.接收到服务器响应的时候调用该方法
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //在该方法中可以得到响应头信息,即response
    NSLog(@"didReceiveResponse--%@",[NSThread currentThread]);

    //注意:需要使用completionHandler回调告诉系统应该如何处理服务器返回的数据
    //默认是取消的
/*
    NSURLSessionResponseCancel = 0,        默认的处理方式,取消
    NSURLSessionResponseAllow = 1,         接收服务器返回的数据
    NSURLSessionResponseBecomeDownload = 2,变成一个下载请求
    NSURLSessionResponseBecomeStream        变成一个流
 */

    completionHandler(NSURLSessionResponseAllow);
}

//2.接收到服务器返回数据的时候会调用该方法,如果数据较大那么该方法可能会调用多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData--%@",[NSThread currentThread]);

    //拼接服务器返回的数据
    [self.responseData appendData:data];
}

//3.当请求完成(成功|失败)的时候会调用该方法 , 如果请求失败 , 则error有值
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"didCompleteWithError--%@",[NSThread currentThread]);

    if(error == nil)
    {
    NSDictionary *dict = [NSJSONSerialization      JSONObjectWithData:self.responseData options:kNilOptions error:nil];
        NSLog(@"%@",dict);
    }
}
@end

你可能感兴趣的:(iOS-发送GET和POST请求)