AFNetWorking3.0

AFHTTPSessionManager的一些配置

形式11. AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];  
2. sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; 

形式23. // 初始化Manager
4. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
5. // 不加上这句话,会报“Request failed: unacceptable content-type: text/plain”错误,因为我们要获取text/plain类型数据
6. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
形式3:

    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    //转换发送数据格式和返回数据格式
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
形式4:
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
    NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
    NSLog(@"%@", cerData);
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSArray alloc] initWithObjects:cerData, nil]];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

形式5//主Url 可以封装起来统一管理,也可以直接写在GET参数里单独管理
    NSURL *baseUrl = [NSURL URLWithString:@"http://apis.baidu.com/"];

    //AFHTTPSessionManager 创建一个网络请求
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:baseUrl];

    // Requests 请求Header参数
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //系统参数
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    //自定义参数
    [manager.requestSerializer setValue:@"fd0a97bd4bcb79b91c50b47c7fa8246d" forHTTPHeaderField:@"apikey"];

    //Responses 响应Header参数
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //系统参数
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];












get - 1

/**
 Creates and runs an `NSURLSessionDataTask` with a `GET` request.

 @param URLString The URL string used to create the request URL.
 @param parameters The parameters to be encoded according to the client request serializer.
 @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
 @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.

 @see -dataTaskWithRequest:completionHandler:
 */
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
                   parameters:(nullable id)parameters
                      success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;

 get - 2

/**
 Creates and runs an `NSURLSessionDataTask` with a `GET` request.

 @param URLString The URL string used to create the request URL.
 @param parameters The parameters to be encoded according to the client request serializer.
 @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
 @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
 @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.

 @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
 */
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
                            parameters:(nullable id)parameters
                              progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
                               success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                               failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;


一些例子:
1.1.
2. // Get请求
3. [manager GET:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
4. // 这里可以获取到目前的数据请求的进度
5. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
6. // 请求成功,解析数据
7. NSLog(@"%@", responseObject);
8. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
9.  
10. NSLog(@"%@", dic);
11. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
12. // 请求失败
13. NSLog(@"%@", [error localizedDescription]);
14. }];


==================================================
例子2
//主Url 可以封装起来统一管理,也可以直接写在GET参数里单独管理
    NSURL *baseUrl = [NSURL URLWithString:@"http://apis.baidu.com/"];

    //AFHTTPSessionManager 创建一个网络请求
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:baseUrl];

    // Requests 请求Header参数
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //系统参数
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    //自定义参数
    [manager.requestSerializer setValue:@"fd0a97bd4bcb79b91c50b47c7fa8246d" forHTTPHeaderField:@"apikey"];

    //Responses 响应Header参数
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //系统参数
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    //参数urlParam 可以设置多个参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setValue:@"深圳" forKey:@"cityname"];
[manager GET:@"apistore/weatherservice/citylist" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = responseObject[@"retData"][0];
        NSLog(@"请求success \n城市Id = %@ \n城市简称 = %@ \n城市中文名 = %@ \n城市拼音 = %@ \n省 = %@",dataDic[@"area_id"],dataDic[@"district_cn"],dataDic[@"name_cn"],dataDic[@"name_en"],dataDic[@"province_cn"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error");
    }];














Post-1

/**
 Creates and runs an `NSURLSessionDataTask` with a `POST` request.

 @param URLString The URL string used to create the request URL.
 @param parameters The parameters to be encoded according to the client request serializer.
 @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
 @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.

 @see -dataTaskWithRequest:completionHandler:
 */
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(nullable id)parameters
                       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;





Post-2
/**
 Creates and runs an `NSURLSessionDataTask` with a `POST` request.

 @param URLString The URL string used to create the request URL.
 @param parameters The parameters to be encoded according to the client request serializer.
 @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
 @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
 @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.

 @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
 */
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
                             parameters:(nullable id)parameters
                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;

一些例子:
1. // 请求的参数
2. NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"20131129", @"date", @"1", @"startRecord", @"5", @"len", @"1234567890", @"udid", @"Iphone", @"terminalType", @"213", @"cid", nil];
3. // 初始化Manager
4. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
5. // 不加上这句话,会报“Request failed: unacceptable content-type: text/plain”错误,因为我们要获取text/plain类型数据
6. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
7. // post请求
8. [manager POST:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?" parameters:dic constructingBodyWithBlock:^(id _Nonnull formData) {
9. // 拼接data到请求体,这个block的参数是遵守AFMultipartFormData协议的。
10. } progress:^(NSProgress * _Nonnull uploadProgress) {
11. // 这里可以获取到目前的数据请求的进度
12. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
13. // 请求成功,解析数据
14. NSLog(@"%@", responseObject);
15. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
16. NSLog(@"%@", dic);
17. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
18. // 请求失败
19. NSLog(@"%@", [error localizedDescription]);
20. }];













Post-3
/**
 Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.

 @param URLString The URL string used to create the request URL.
 @param parameters The parameters to be encoded according to the client request serializer.
 @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
 @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
 @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.

 @see -dataTaskWithRequest:completionHandler:
 */
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(nullable id)parameters
     constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
                       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;

Post-4
/**
 Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.

 @param URLString The URL string used to create the request URL.
 @param parameters The parameters to be encoded according to the client request serializer.
 @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
 @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
 @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
 @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.

 @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
 */
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
                             parameters:(nullable id)parameters
              constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用AFNetworking库下载文件时,有几种常见的方式。第一种方式是使用AFHTTPRequestOperation进行文件下载,需要传入文件的下载地址URL、自定义的文件名fileName以及下载到的文件路径d_path。 另一种方式是使用AFHTTPSessionManager结合NSURLSessionDownloadTask进行文件下载。同样需要传入文件的下载地址URL和下载到的文件路径d_path。 此外,还可以使用AFNetworking库来实现文件的断点下载功能。通过对AFNetworking3.0版本的学习,你可以了解到如何使用AFNetworking库来实现文件断点下载,并且可以获取一些有价值的参考信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [AFNetworking从指定网址下载文件的两种方式总结](https://blog.csdn.net/u014063717/article/details/52232858)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [iOS利用AFNetworking3.0——实现文件断点下载](https://download.csdn.net/download/weixin_38607784/12786948)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值