asihttp 源码分析 之二 main
一:main
main方法中上来就给你锁住了
[[self cancelledLock] lock]
在方法的最后解锁
[[self cancelledLock] unlock]
// A HEAD request generated by an ASINetworkQueue may have set the error already. If so, we should not proceed.//这个方法为使用ASINetworkQueue 队列是的专用方法,在发起同步请求时毫无意义
if ([self error]) {
[selfsetComplete:YES];
[selfmarkAsFinished];
return;
}[self setComplete:NO];
[selfsetDidUseCachedResponse:NO];
//检测url是否为nil
if(![selfurl]){
[selffailWithError:ASIUnableToCreateRequestError];
return;
}
//Mustcallbeforewecreatetherequestsothattherequestmethodcanbesetifneedsbe
//当发起的同步请求时mainRequest一定是为nil的。只有在使用 ASINetworkQueue 时,mainRequest的值才是有意义的if (![self mainRequest]) {
[selfbuildPostBody];//改方法的工作很重要,下面介绍一下
}
//如果不是get请求方式,使用DownloadCache是不可以的,所以在这里设置为nil。
if(![[selfrequestMethod]isEqualToString:@"GET"]){
[selfsetDownloadCache:nil];
}2:buildPostBody 方法
// This function will be called either just before a request starts, or when postLength is needed, whichever comes first// postLength must be set by the time this function is complete
-(void)buildPostBody
{//haveBuiltPostBody 一个标志,默认为no。
if ([self haveBuiltPostBody]) {
return;
}
//Arewesubmittingtherequestbodyfromafileondisk
if([selfpostBodyFilePath]){
//IfwewerewritingtothepostbodyviaappendPostDataorappendPostDataFromFile,closethewritestream
if([selfpostBodyWriteStream]){
[[selfpostBodyWriteStream]close];
[selfsetPostBodyWriteStream:nil];
}
NSString*path;
if([selfshouldCompressRequestBody]){
if(![selfcompressedPostBodyFilePath]){
[selfsetCompressedPostBodyFilePath:[NSTemporaryDirectory()stringByAppendingPathComponent:[[NSProcessInfoprocessInfo]globallyUniqueString]]];
NSError*err=nil;
if(![ASIDataCompressorcompressDataFromFile:[selfpostBodyFilePath]toFile:[selfcompressedPostBodyFilePath]error:&err]){
[selffailWithError:err];
return;
}
}
path=[selfcompressedPostBodyFilePath];
}else{
path=[selfpostBodyFilePath];
}
NSError*err=nil;
[selfsetPostLength:[[[[[NSFileManageralloc]init]autorelease]attributesOfItemAtPath:patherror:&err]fileSize]];
if(err){
[selffailWithError:[NSErrorerrorWithDomain:NetworkRequestErrorDomaincode:ASIFileManagementErroruserInfo:[NSDictionarydictionaryWithObjectsAndKeys:[NSStringstringWithFormat:@"Failedtogetattributesforfileatpath'%@'",path],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
return;
}
//Otherwise,wehaveanin-memoryrequestbody
}else{
if([selfshouldCompressRequestBody]){
NSError*err=nil;
NSData*compressedBody=[ASIDataCompressorcompressData:[selfpostBody]error:&err];
if(err){
[selffailWithError:err];
return;
}
[selfsetCompressedPostBody:compressedBody];
[selfsetPostLength:[[selfcompressedPostBody]length]];
}else{
[selfsetPostLength:[[selfpostBody]length]];
}
}
if([selfpostLength]>0){
if([requestMethodisEqualToString:@"GET"]||[requestMethodisEqualToString:@"DELETE"]||[requestMethodisEqualToString:@"HEAD"]){
[selfsetRequestMethod:@"POST"];
}
[selfaddRequestHeader:@"Content-Length"value:[NSStringstringWithFormat:@"%llu",[selfpostLength]]];
}
[self setHaveBuiltPostBody:YES];}
该方法会设置一下http请求头信息,如果设置了postbodyfilepath,requestmethod 会被设置为post方式。
回到main方法,看一下缓存判断的地方
if ([self downloadCache]) {
// If this request should use the default policy, set its policy to the download cache's default policy
if(![selfcachePolicy]){
[selfsetCachePolicy:[[selfdownloadCache]defaultCachePolicy]];
}// If have have cached data that is valid for this request, use that and stop
if([[selfdownloadCache]canUseCachedDataForRequest:self]){
[selfuseDataFromCache];
return;
}// If cached data is stale, or we have been told to ask the server if it has been modified anyway, we need to add headers for a conditional GET if ([self cachePolicy] & (ASIAskServerIfModifiedWhenStaleCachePolicy|ASIAskServerIfModifiedCachePolicy)) {
NSDictionary *cachedHeaders = [[self downloadCache] cachedResponseHeadersForURL:[self url]];
if(cachedHeaders){
NSString*etag=[cachedHeadersobjectForKey:@"Etag"];
if(etag){
[[selfrequestHeaders]setObject:etagforKey:@"If-None-Match"];
}
NSString*lastModified=[cachedHeadersobjectForKey:@"Last-Modified"];
if(lastModified){
[[selfrequestHeaders]setObject:lastModifiedforKey:@"If-Modified-Since"];
}
}
}
}首先来看一下 downloadCache是怎么设置的,还记得- (id)initWithURL:(NSURL *)newURL方法吗?? 在这个方法里有这么一句 [self setDownloadCache:[[self class] defaultCache]];
defaultCache默认为nil。所以如果要使用cache必须手动设置,默认是不使用如何cache的。
关于 ASIDownloadCache 我们后面介绍。
该方法主要是从本地cache中取得一个和http头文件相关的属性If-None-Match、Last-Modified,等等,是为了http header文件的组合。
权限验证
[self applyAuthorizationHeader];
该方法从 findSessionAuthenticationCredentials 、username、 password、domain 查找信息 添加到requestHeaders中,用于http组合header。
好了,经过以上几步繁琐的过程,http 头文件的信息,终于差不多了,下面是最重要的一步了。
if ([self configureProxies]) {
[selfstartRequest];
}[self configureProxies] 设置代理。
[self startRequest]; 请求开始了。