asihttp 源码分析 之二 main

本文深入解析了HTTP请求的核心方法,包括main方法中的锁操作、同步请求处理、缓存检查、权限验证及代理配置等关键步骤。通过详细分析每个阶段的作用,帮助开发者更好地理解HTTP请求的内部运作机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一: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]; 请求开始了。

 

内容概要:本文介绍了基于Python实现的SSA-GRU(麻雀搜索算法优化门控循环单元)时间序列预测项目。项目旨在通过结合SSA的全局搜索能力和GRU的时序信息处理能力,提升时间序列预测的精度和效率。文中详细描述了项目的背景、目标、挑战及解决方案,涵盖了从数据预处理到模型训练、优化及评估的全流程。SSA用于优化GRU的超参数,如隐藏层单元数、学习率等,以解决传统方法难以捕捉复杂非线性关系的问题。项目还提供了具体的代码示例,包括GRU模型的定义、训练和验证过程,以及SSA的种群初始化、迭代更新策略和适应度评估函数。; 适合人群:具备一定编程基础,特别是对时间序列预测和深度学习有一定了解的研究人员和技术开发者。; 使用场景及目标:①提高时间序列预测的精度和效率,适用于金融市场分析、气象预报、工业设备故障诊断等领域;②解决传统方法难以捕捉复杂非线性关系的问题;③通过自动化参数优化,减少人工干预,提升模型开发效率;④增强模型在不同数据集和未知环境中的泛化能力。; 阅读建议:由于项目涉及深度学习和智能优化算法的结合,建议读者在阅读过程中结合代码示例进行实践,理解SSA和GRU的工作原理及其在时间序列预测中的具体应用。同时,关注数据预处理、模型训练和优化的每个步骤,以确保对整个流程有全面的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值