网络请求原理

一、网络框架

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");
}

你可能感兴趣的:(网络请求原理)