美文网首页
网络请求数据并且解析的过程(推荐AFNetworking)

网络请求数据并且解析的过程(推荐AFNetworking)

作者: 精神薇 | 来源:发表于2016-12-22 20:34 被阅读0次

    demo
    1.http请求,get同步异步,post同步异步
    get同步

    //先把中文编码
        NSString *str = @"http://apis.juhe.cn/cook/query?key=5c7bb350799fb1b79485e2c040c3289a&menu=红烧肉";
        NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
        NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
    //处理请求
        NSURL *url = [NSURL URLWithString:result];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    

    get异步

    //把中文编码代码
        NSString *str = @"http://apis.juhe.cn/cook/query?key=5c7bb350799fb1b79485e2c040c3289a&menu=红烧肉";
        NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
        NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
    //处理请求
        NSURL *url = [NSURL URLWithString:result];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            if(data!=nil){
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                
            }
            if(connectionError!=nil){
                NSLog(@"%@",[connectionError description]);
            }
            if(data==nil&&connectionError==nil){
                       NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                       NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                       NSLog(@"HttpResponseCode:%ld", responseCode);
                       NSLog(@"HttpResponseBody %@",responseString);
            }
        }];
    

    post异步

    //把中文编码代码
        NSString *str = @"http://apis.juhe.cn/cook/query?key=5c7bb350799fb1b79485e2c040c3289a&menu=红烧肉";
        NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
        NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
    //处理请求
        NSURL *url = [NSURL URLWithString:result];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        [request setHTTPMethod:@"POST"];
        NSString *str1 = @"type=focus-c";
        NSData *data = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        [NSURLConnection sendAsynchronousRequest:request queue:   [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            if(data!=nil){
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                
            }
            if(connectionError!=nil){
                NSLog(@"%@",[connectionError description]);
            }
            if(data==nil&&connectionError==nil)
                NSLog(@"null data");
        }];
    

    2.session解析
    (1).类似于NSURLConnection

    NSString *a = [NSString stringWithFormat:@"page=%d",i+1];
    NSString *st =@"http://apis.baidu.com/showapi_open_bus/weixin/weixin_article_list?";
    NSString *str = [NSString stringWithFormat:@"%@%@",st,a];
    //中文编码
    NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
    //处理请求
    NSURL *url = [NSURL URLWithString:result];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"ebdce978ac5a698d60d4048fce2d50cb" forHTTPHeaderField: @"apikey"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
    }];
    //发送
    [task resume];
    

    (2).服从协议,代理方法获取数据

    //协议
    <NSURLSessionDataDelegate>
    //data属性
    @property(nonatomic,retain)NSMutableData *mutableData;
    //把中文编码代码
        NSString *str = @"http://apis.juhe.cn/cook/query?key=5c7bb350799fb1b79485e2c040c3289a&menu=红烧肉";
        NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
        NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
    //处理请求
        NSURL *url = [NSURL URLWithString:result];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        [request setHTTPMethod:@"POST"];
        NSString *str1 = @"type=focus-c";
        NSData *data = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
    //SessionConfiguration 
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
        NSURLSessionTask *task =[session dataTaskWithRequest:request];
        self.mutableData = [NSMutableData data];
        [task resume];
    
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
        [self.mutableData appendData:data];
    }
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse * _Nullable))completionHandler{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.mutableData options:0 error:nil];
    
    }
    

    3.AFNetworking

        NSString *str=@"http://apis.juhe.cn/cook/query";
        NSDictionary *dic=@{@"menu":@"红烧肉",@"key":@"5c7bb350799fb1b79485e2c040c3289a"};
        NSMutableURLRequest *requrst=[[AFHTTPRequestSerializer serializer]requestWithMethod:@"GET" URLString:str parameters:dic error:nil];
        NSURLSessionConfiguration *con=[NSURLSessionConfiguration defaultSessionConfiguration];
        AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc]initWithSessionConfiguration:con];
        NSURLSessionDataTask *dataTast=[manager dataTaskWithRequest:requrst completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (error) {
                NSLog(@"Error:%@",error);
            }
            else
            {
                NSDictionary *dic=responseObject;
                //NSLog(@"dic1==%@",dic1);
               // NSString *ss=[[NSString alloc]initWithData:dic1 encoding:NSUTF8StringEncoding];
            }
        }];
        [dataTast resume];
    

    相关文章

      网友评论

          本文标题:网络请求数据并且解析的过程(推荐AFNetworking)

          本文链接:https://www.haomeiwen.com/subject/xtuhvttx.html