[AFNetworking]源代码分析--AFURLRequestSerialization.h

AFNetworking framework includes:
AFURLRequestSerialization.h
AFURLResponseSerialization.h
AFSecurityPolicy.h
AFNetworkReachabilityManager.h
AFURLConnectionOperation.h
AFHTTPRequestOperation.h
AFHTTPRequestOperationManager.h
AFURLSessionManager.h
AFHTTPSessionManager.h

AFURLRequestSerialization.h

protocal AFURLRequestSerialization:该协议若被采用则需要实现其

- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
	 withParameters:(nullable id)parameters
	error:(NSError * __nullable __autoreleasing *)error;

方法,该方法将一个请求 序列化 为指定 类型的请求 比如JSON 请求,将请求体序列化为JSON类型,并将Content-Type 设置为application/json。实现方法有三个,其中一个基方法 所在于AFURLRequestSerializer类 剩下的分别为AFJSONRequestSerializer,和AFPropertyListRequestSerializer。




protocol AFMultipartFormData 该协议定义了 AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:中block参数所支持的方法
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
                     name:(NSString *)name
                     error:(NSError * __nullable __autoreleasing *)error;

该方法根据fileURL解析文件名字和扩展名,然后调用内部方法 fileURL即文件在sandbox中的地址,name对英语服务器接受到的映射属性名,fileName文件的真实名,mineType文件类型,以下方法即以上方法最后的调用。
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
                     name:(NSString *)name
                     fileName:(NSString *)fileName
                     mimeType:(NSString *)mimeType
                      error:(NSError * __nullable __autoreleasing *)error;



- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
                         name:(NSString *)name
                         fileName:(NSString *)fileName
                         length:(int64_t)length
                         mimeType:(NSString *)mimeType;


方法在http header中添加Content-Dispositon:file;filename=#{filename};name=#{name}以及Content-Type:#{mineType} 以流的形式将数据发送给服务器
 - (void)appendPartWithFileData:(NSData *)data
 		name:(NSString *)name
		fileName:(NSString *)fileName
		mimeType:(NSString *)mimeType;


以NSData发送数据给服务器 


interface AFHTTPRequestSerializer 实现了 AFURLRequestSerialization
包含属性 @property (nonatomic, assign) NSStringEncoding stringEncoding 默认NSUTF8StringEncoding 该属性指定以何种加密方式序列化参数
@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; 缓存策略
@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; 是否处理cookies
@property (nonatomic, assign) NSTimeInterval timeoutInterval; 连接请求超时间隔

类方法+ (instancetype)serializer; 调用其内部 + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions 方法

实例化方法

- (void)setValue:(nullable NSString *)value
				forHTTPHeaderField:(NSString *)field;


为Http头设置属性

- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;

  得到http header的某个属性

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


该方法返回一个NSMutableURLRequest 封装了request 一些属性

method 主要包括GET POST DELETE 等,URLString 主要是访问的url的基地址,然后根据GET还是POST将parameters 选择添加在url里还是request body里面





- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
                                      URLString:(NSString *)URLString
                                       parameters:(nullable NSDictionary *)parameters
                            	       constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
                                       error:(NSError * __nullable __autoreleasing *)error;




mutipartForm的Request 将会自动以流的方式传输给服务器,从URLString所指向的位置读取数据到http body中。返回值NSMutableRequest含有一个HTTPBodyStream属性,来专门处理流数据,以防止设置参数使得数据流清除
其中的block属性 必须是一个接受AFMultipartFormData协议的对象。

- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
                             writingStreamContentsToFile:(NSURL *)fileURL
                             completionHandler:(nullable void (^)(NSError *error))handler;


获得url数据流 然后写入特定url的文件



AFJSONRequestSerializer和AFPropertyListRequestSerializer 都继承自 AFHTTPRequestSerializer

所以不再赘述,只有部分细节处理上存在差异






具体代码分析


//根据method 和parameters 设置request ,返回的request 是份copy
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                               withParameters:(id)parameters
                                        error:(NSError *__autoreleasing *)error
{
    NSParameterAssert(request);
    NSMutableURLRequest *mutableRequest = [request mutableCopy];


    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
	//枚举属性,如果属性值不存在 则给request设置上去
        if (![request valueForHTTPHeaderField:field]) {
            [mutableRequest setValue:value forHTTPHeaderField:field];
        }
    }];
	//如果有参数 设置	
    if (parameters) {
        NSString *query = nil;
        if (self.queryStringSerialization) {
            NSError *serializationError;
            query = self.queryStringSerialization(request, parameters, &serializationError);


            if (serializationError) {
                if (error) {
                    *error = serializationError;
                }


                return nil;
            }
        } else {
            switch (self.queryStringSerializationStyle) {
                case AFHTTPRequestQueryStringDefaultStyle:
                    query = AFQueryStringFromParameters(parameters);
                    break;
            }
        }
	//根据method 设置header 的contentType,URL
        if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
            mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
        } else {
            if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
                [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            }
            [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
        }
    }


    return mutableRequest;
}



		
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                   URLString:(NSString *)URLString
                   parameters:(id)parameters
                   error:(NSError *__autoreleasing *)error
{
		    NSParameterAssert(method);
		    NSParameterAssert(URLString);
		    NSURL *url = [NSURL URLWithString:URLString];
		    NSParameterAssert(url);
			//根据url创建request,并设置HTTPmethod
		    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
		    mutableRequest.HTTPMethod = method;
			//AFHTTPRequestSerializerObservedKeyPaths()方法返回默认配置,然后设置新的配置
		    for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
		        if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
		            [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
        		}
   		 }
			//配置request 属性
   		 mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];


		return mutableRequest;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值