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]) {
   [self setComplete:YES];
   [self markAsFinished];
   return;  
  }

 

  [self setComplete:NO];
  [self setDidUseCachedResponse:NO];
  

//检测url是否为nil
  if (![self url]) {
   [self failWithError:ASIUnableToCreateRequestError];
   return;  
  }
  
  // Must call before we create the request so that the request method can be set if needs be
//当发起的同步请求时mainRequest一定是为nil的。只有在使用  ASINetworkQueue 时,mainRequest的值才是有意义的

if (![self mainRequest]) {
   [self buildPostBody]; //改方法的工作很重要,下面介绍一下
  }
  

//如果不是get请求方式,使用DownloadCache是不可以的,所以在这里设置为nil。
  if (![[self requestMethod] isEqualToString:@"GET"]) {
   [self setDownloadCache: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;
 }
 
 // Are we submitting the request body from a file on disk
 if ([self postBodyFilePath]) {
  
  // If we were writing to the post body via appendPostData or appendPostDataFromFile, close the write stream
  if ([self postBodyWriteStream]) {
   [[self postBodyWriteStream] close];
   [self setPostBodyWriteStream:nil];
  }

  
  NSString *path;
  if ([self shouldCompressRequestBody]) {
   if (![self compressedPostBodyFilePath]) {
    [self setCompressedPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
    
    NSError *err = nil;
    if (![ASIDataCompressor compressDataFromFile:[self postBodyFilePath] toFile:[self compressedPostBodyFilePath] error:&err]) {
     [self failWithError:err];
     return;
    }
   }
   path = [self compressedPostBodyFilePath];
  } else {
   path = [self postBodyFilePath];
  }
  NSError *err = nil;
  [self setPostLength:[[[[[NSFileManager alloc] init] autorelease] attributesOfItemAtPath:path error:&err] fileSize]];
  if (err) {
   [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to get attributes for file at path '%@'",path],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
   return;
  }
  
 // Otherwise, we have an in-memory request body
 } else {
  if ([self shouldCompressRequestBody]) {
   NSError *err = nil;
   NSData *compressedBody = [ASIDataCompressor compressData:[self postBody] error:&err];
   if (err) {
    [self failWithError:err];
    return;
   }
   [self setCompressedPostBody:compressedBody];
   [self setPostLength:[[self compressedPostBody] length]];
  } else {
   [self setPostLength:[[self postBody] length]];
  }
 }
  
 if ([self postLength] > 0) {
  if ([requestMethod isEqualToString:@"GET"] || [requestMethod isEqualToString:@"DELETE"] || [requestMethod isEqualToString:@"HEAD"]) {
   [self setRequestMethod:@"POST"];
  }
  [self addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%llu",[self postLength]]];
 }
     [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 (![self cachePolicy]) {
    [self setCachePolicy:[[self downloadCache] defaultCachePolicy]];
   }

   // If have have cached data that is valid for this request, use that and stop
   if ([[self downloadCache] canUseCachedDataForRequest:self]) {
    [self useDataFromCache];
    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 = [cachedHeaders objectForKey:@"Etag"];
     if (etag) {
      [[self requestHeaders] setObject:etag forKey:@"If-None-Match"];
     }
     NSString *lastModified = [cachedHeaders objectForKey:@"Last-Modified"];
     if (lastModified) {
      [[self requestHeaders] setObject:lastModified forKey:@"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]) {
   [self startRequest];
  }

 

[self configureProxies] 设置代理。

 

 [self startRequest]; 请求开始了。

 

你可能感兴趣的:(http)