网络请求原理

一、网络框架

1、ASIHttpRequest:底层用C实现,基于CFNetwork
2、AFNetwork:3.0以前基于NSURLConection,3.0以后是基于NSURLSession。

二、URL组成

协议(http/https/ftp) + IP(112.124.39.131:8081) + 接口路径(ediantong-api/apiGateway)+参数。

http://112.124.39.131:8081/ediantong-api/apiGateway?method=nepbaby.user.create&identity=13036780808&bizContent={"code":"219518","phone":"13828871001","name":"1001-店员","sex":"F","jobNumber":1001}&sign=token123456

三、网络请求

1、get网络请求
get 的URL有中文的话,需要用base64进行转码

    NSString * urlStr = [NSString stringWithFormat:@"%@?versions_id=1&system_type=1",URLPath];
    NSURL * url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"GET"];
    [request setHTTPBody:nil];
    NSURLSession * session = [NSURLSession sharedSession];
    //NSURLSession 创建的task挂起的
    NSURLSessionDataTask * task = [session  dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary * infoDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",infoDict); 
    }];
    [task resume];

2、post网络请求

    NSURL * url = [NSURL URLWithString:URLPath];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString * postStr =  @"versions_id=1&system_type=1";
    [request setHTTPBody:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSession * session = [NSURLSession sharedSession];
    //NSURLSession 创建的task挂起的
    NSURLSessionDataTask * task = [session  dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary * infoDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",infoDict);
    }];
    [task resume];

3、使用代理形式请求数据

- (void)netLoadDelegate{
    NSURL * url = [NSURL URLWithString:URLPath];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString * postStr =  @"versions_id=1&system_type=1";
    [request setHTTPBody:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    //1、网络缓存的配置
    //defaultSessionConfiguration,放在磁盘里面(disk),放在文件(cache)里。
    //ephemeralSessionConfiguration;临时缓存,生存周期是跟随app的过程。
    //后台模式
    //+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier;
    //delegateQueue为nil是在默认队列中开启,在didReceiveData的代理方法中,打印线程,会显示子线程。
    //NSURLSession 只有异步的请求
    NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:self delegateQueue:nil];
    
    NSURLSessionTask * task = [session dataTaskWithRequest:request];
    //开启任务
    [task resume];
}
#pragma mark delegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    
}
//数据请求完成成的代理方法
- (void)URLSession:(NSURLSession *)session task:(nonnull NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{
    //如果这里的线程不是主线程,并且需要刷新界面的话,需要回到主线程去刷新UI
}
//请求头的响应 图片/视频上传 做进度条等
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    //在NSURLConnection中,不需要写回调,在NSURLSession中不写回调,默认是不接受数据的,
    completionHandler(NSURLSessionResponseAllow);
}

4、如何使用NSURLSession做同步数据请求。
当信号量小于或者等于0是,dispatch_wait(sema, DISPATCH_TIME_FOREVER);会一直等待,直到dispatch_semaphore_signal(sema);使信号量加一为止。注:当执行dispatch_wait时信号量会减1.

- (void)getNetwork{
    NSString * urlStr = [NSString stringWithFormat:@"%@?versions_id=1&system_type=1",URLPath];
    NSURL * url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"GET"];
    [request setHTTPBody:nil];
    NSURLSession * session = [NSURLSession sharedSession];
    //创建一个信号量
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSLog(@"Net ~ Begin");
    //NSURLSession 创建的task挂起的
    NSURLSessionDataTask * task = [session  dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary * infoDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"Net ~ ing");
        dispatch_semaphore_signal(sema);
    }];
    [task resume];
    dispatch_wait(sema, DISPATCH_TIME_FOREVER);   
    NSLog(@"Net ~ End");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 客户端怎样与服务器通信?客户端怎样找到服务器?客户端与服务器间怎样传递数据? 一、URL的组成(找到服务器) UR...
    消费后生产阅读 1,361评论 0 0
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,203评论 30 471
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,420评论 0 6
  • 为了背诵词而准备的文集,每一首都是古代人的心血,当我开始尝试站在那些词人的角度去看他们的词时候,十分吃力。这些才华...
    简单的弃子阅读 216评论 0 0
  • 文/陶蓉 萧红,原名张迺莹,中国近代女作家,“民国四大才女”之一.为四大才女中命运最为悲苦的一位传奇性人物。她短暂...
    陶蓉子阅读 469评论 4 4