AFNetWorking 网络请求框架学习

页面标题 空间 更新于

{0}

{0} {3} {5} 转至元数据结尾
转至元数据起始

  • 1英文文档:http://cocoadocs.org/docsets/AFNetworking/3.1.0/index.html
  • 2AFHTTPRequestSerializer
    • 2.1配置HTTP请求标题
    • 2.2此外AFHTTPRequestSerializer中含有多种请求方法:
  • 3AFJSONRequestSerializer
  • 4AFHTTPResponseSerializer
    • 4.1配置响应序列化
  • 5AFJSONResponseSerializer
  • 6AFHTTPSessionManager
      • 6.1.1    属性
      • 6.1.2    初始化
      • 6.1.3   制作HTTP请求
    • 6.2 使用获取text/html内容:
    • 6.3使用获取text/json内容:
    • 6.4 请求安全策略:
    • 6.5文件下载:
    • 6.6文件上传:
    • 6.7文件上传加进度
    • 6.8网络状态检测
    • 6.9请求字段赋值:

英文文档:http://cocoadocs.org/docsets/AFNetworking/3.1.0/index.html

AFHTTPRequestSerializer

 

AFHTTPRequestSerializer符合AFURLRequestSerializationAFURLResponseSerialization协议,提供查询字符串/ URL形式编码的参数序列化和默认请求标头,以及响应状态码和内容类型验证的具体基本实现。鼓励处理HTTP的任何请求或响应序列化程序进行子类化AFHTTPRequestSerializer,以确保一致的默认行为。

AFHTTPRequestSerializer是用于构建NSURLRequest的类,通过-init:方法进行初始化,指定编码方式为NSUTF-8。包含对HTTP请求分为请求头和请求体的设置。

 

配置HTTP请求标题

 

  •   HTTPRequestHeaders  
  • + serializer
  • – setValue:forHTTPHeaderField:
  • – valueForHTTPHeaderField:
  • – setAuthorizationHeaderFieldWithUsername:password:
  • – clearAuthorizationHeader

此外AFHTTPRequestSerializer中含有多种请求方法:

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLStringparameters:(nullable id)parameters error:(NSError *_Nullable __autoreleasing *)error

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLStringparameters:(nullable id)parameters error:(NSError *_Nullable __autoreleasing *)error

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLStringparameters:(nullable id)parameters error:(NSError *_Nullable __autoreleasing *)error

 


AFJSONRequestSerializer

AFJSONRequestSerializer是的一个子类AFHTTPRequestSerializer,使用编码参数作为JSON NSJSONSerialization,设置Content-Type所述编码请求的application/json

+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions

 

 


AFHTTPResponseSerializer

 

AFHTTPResponseSerializer符合AFURLRequestSerializationAFURLResponseSerialization协议,提供查询字符串/ URL形式编码的参数序列化和默认请求标头,以及响应状态码和内容类型验证的具体基本实现。鼓励处理HTTP的任何请求或响应序列化程序进行子类化AFHTTPResponseSerializer,以确保一致的默认行为。

配置响应序列化

  •   acceptableStatusCodes 属性
  •   acceptableContentTypes 属性
  • – validateResponse:data:error:
  •   stringEncoding 属性
  • + serializer

对于内容格式及内容编码可以在这里修改


AFJSONResponseSerializer

AFJSONResponseSerializerAFHTTPResponseSerializer验证和解码JSON响应的子类。

默认情况下,AFJSONResponseSerializer接受以下MIME类型(包括官方标准)application/json以及其他常用类型:

  • application/json
  • text/json
  • text/javascript

+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions


AFHTTPSessionManager

 

封装了AFHTTPRequestSerializer与AFHTTPResponseSerializer 将一切请求网络的操作更加简单化。

    属性

  •   baseURL 属性
  •   requestSerializer 属性
  •   responseSerializer 属性

    初始化

  • + manager
  • – initWithBaseURL:
  • – initWithBaseURL:sessionConfiguration:

   制作HTTP请求

  • – GET:parameters:success:failure:
  • – GET:parameters:progress:success:failure:
  • – HEAD:parameters:success:failure:
  • – POST:parameters:success:failure:
  • – POST:parameters:progress:success:failure:
  • – POST:parameters:constructingBodyWithBlock:success:failure:
  • – POST:parameters:constructingBodyWithBlock:progress:success:failure:
  • – PUT:parameters:success:failure:
  • – PATCH:parameters:success:failure:
  • – DELETE:parameters:success:failure:
 

 使用获取text/html内容:

AFNetworking会默认的将返回认为是json的结果去解析,然后没有办法解析成功,所以就会报错误。
fails Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
看源码:

- (instancetype)initWithBaseURL:(NSURL *)url

           sessionConfiguration:(NSURLSessionConfiguration *)configuration

{

    self = [super initWithSessionConfiguration:configuration];

    if (!self) {

        return nil;

    }

 

    // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected

    if ([[url pathlength] > 0 && ![[url absoluteStringhasSuffix:@”/”]) {

        url = [url URLByAppendingPathComponent:@”“];

    }

 

    self.baseURL = url;

 

    self.requestSerializer = [AFHTTPRequestSerializer serializer]; //请求默认以http格式

    self.responseSerializer = [AFJSONResponseSerializer serializer];//响应默认以json格式

 

    return self;

}

 

下面是解决的方法:

 

#pragma  mark - 获取 text\html格式数据

- (void)AFNet2

{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//序列化操作

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@”text/html”];

    [manager GET:@”http://www.baidu.com” parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

NSLog(@”%@”,responseObject);//二进制数据

        NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];//转utf-8

NSLog(@”%@”,result);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

NSLog(@”%@”,error);

    }];

 

}

 

使用获取text/json内容:

- (void)AFNJson

{

    

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager GET:@”http://xxx.json” parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@”%@”,responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@”%@”,error);

    }];

    

}

 

 请求安全策略:

- (void)AFNHttps{

    

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];

    securityPolicy.allowInvalidCertificates = YES;

    manager.securityPolicy = securityPolicy;

    [manager GET:@”http://xxx.json” parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@”%@”,responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@”%@”,error);

    }];

 

}



文件下载:

 

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];


文件上传:

 

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];


文件上传加进度

 

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

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

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];

[uploadTask resume];


网络状态检测

 

- (void)AFNetWorkState

{

 

    [[AFNetworkReachabilityManager sharedManagersetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

 

        NSLog(@”Reachability: %@”AFStringFromNetworkReachabilityStatus(status));

 

    }];

 

    

 

    [[AFNetworkReachabilityManager sharedManagerstartMonitoring];

 

}


请求字段赋值:

 NSString *URLString = @”http://example.com;

NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

 

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

 

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3

 

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

 







 

你可能感兴趣的:(ios,iOS,AFNetWorking)