iOS学习笔记-----AFNetworking的使用

1.GET请求

NSString *urlString = @"http://piao.163.com/m/cinema/list.html?app_id=1&mobileType=iPhone&ver=2.6&channel=appstore&deviceId=9E89CB6D-A62F-438C-8010-19278D46A8A6&apiVer=6&city=110000";
    //------------------------使用AF Get操作------------------------
    //创建manager
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];

    //设置发送和接收的数据类型
    //发送数据格式
    //AFHTTPRequestSerializer 使用 key1=value1&key2=value2的形式来上传数据 默认
    //AFJSONRequestSerializer 使用Json格式上传数据
    //[AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];

    //接受数据格式
    //AFHTTPResponseSerializer 不做解析操作
    //AFJSONResponseSerializer 自动进行Json解析  默认
    //AFXMLParserResponseSerializer 接受XML数据
    manger.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableLeaves];

    //发起请求
    [manger GET:urlString
     parameters:nil
       progress:^(NSProgress * _Nonnull downloadProgress) {
           NSLog(@"%lli/%lli", downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
       }
        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"请求成功");
            NSLog(@"responseObject%@", responseObject);
        }
        failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];

2.POST请求

(1)普通POST请求

//创建manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    NSString *urlString = @"http://piao.163.com/m/cinema/schedule.html?app_id=1&mobileType=iPhone&ver=2.6&channel=appstore&deviceId=9E89CB6D-A62F-438C-8010-19278D46A8A6&apiVer=6&city=110000";
    NSDictionary *parameters = @{@"cinema_id" : @"1533"};


    //发起POST请求
    [manager POST:urlString
       parameters:parameters
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              NSLog(@"请求成功:%@", responseObject);
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@"请求失败");
          }];

(2)微博接口,multipart/form-data POST文件上传

  //url token
    NSString *urlString = @"https://upload.api.weibo.com/2/statuses/upload.json";
    //微博身份识别码
    NSString *token = @"2.00hd363CtKpsnBedca9b3f35tBYiP";


    //包装参数字典
    NSDictionary *dic = @{@"access_token" : token, @"status" : @"明天高考!  "};

    //创建manager 发送POST请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager POST:urlString
       parameters:dic
constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //拼接需要上传的数据
    //读取图片
    UIImage *image = [UIImage imageNamed:@"1.jpg"];
    NSData *data = UIImageJPEGRepresentation(image, 0.7);
    //将图片数据 拼接到fromdata中
    [formData appendPartWithFileData:data name:@"pic" fileName:@"1.jpg" mimeType:@"image/jpeg"];
}
         progress:^(NSProgress * _Nonnull downloadProgress) {
             NSLog(@"%lli/%lli", downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
         }
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              NSLog(@"上传成功");
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@"上传失败");
          }];

3.下载任务


    //下载地址
    NSString *urlString = @"http://218.76.27.57:8080/chinaschool_rs02/135275/153903/160861/160867/1370744550357.mp3";

    //创建manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //创建请求对象
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];


    //创建下载任务
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%lli/%lli", downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //接受到响应头,需要制定保存路径
        NSLog(@"状态码:%li", ((NSHTTPURLResponse *)response).statusCode);
        //targetPath 零时文件保存路径
        //返回值 指定的保存路径
        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/菊花台.mp3"];
        NSLog(@"%@", filePath);
        //创建一个沙盒路径下的子路径,设定保存的文件夹位置
        return [NSURL fileURLWithPath:filePath];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"下载完成");
    }];

    [downloadTask resume];

    //绑定任务,到进度显示视图
    [_progressView setProgressWithDownloadProgressOfTask:downloadTask animated:YES];

4.上传任务 multipart/form-data POST文件上传


    NSString *urlString = @"https://api.weibo.com/2/statuses/upload.json";
    NSString *token = @"2.00hd363CtKpsnBedca9b3f35tBYiP";
    //获取输入的文字和图片
    UIImage *image = _imageView.image;
    NSString *text = _textField.text;

    if (image == nil || text.length == 0) {
        return;
    }
    //构造参数字典
    NSDictionary *dic = @{@"access_token" : token,
                          @"status" : text};

    //创建序列化对象
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    //创建请求对象
    NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        //图片数据的拼接
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        [formData appendPartWithFileData:imageData name:@"pic" fileName:@"image.png" mimeType:@"image/png"];

    } error:nil];

    //创建manager
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    //创建上传任务
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {

        //回到主线程中 刷新界面
//        [_progressView performSelectorOnMainThread:@selector(setProgress:) withObject:@(uploadProgress.fractionCompleted) waitUntilDone:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            //Update the progress view
            [_progressView setProgress:uploadProgress.fractionCompleted];
        });

    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        NSLog(@"上传结束,状态码:%li", ((NSHTTPURLResponse *)response).statusCode);
    }];

    [uploadTask resume];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值