设置请求超时时间(timeoutInterval)不起作用

方法一:
解决办法:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];


manager.responseSerializer = [AFHTTPResponseSerializer serializer];


// 设置超时时间

[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];

manager.requestSerializer.timeoutInterval = 15.0f;

[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];

使用方法一用以以下方法下载文件不起作用,之后使用方法二,设置请求的超时时间起作用了

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
   NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:<#(nonnull NSURLRequest *)#> progress:<#^(NSProgress * _Nonnull downloadProgress)downloadProgressBlock#> destination:<#^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response)destination#> completionHandler:<#^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error)completionHandler#>]

方法二:

  NSURL *url = [NSURL URLWithString:urlPath];
  NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:180];

NSMutableURLRequest实现Post请求及其timeoutInterval不生效问题解决

NSData *bodyData = [[bodyString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]dataUsingEncoding:NSUTF8StringEncoding];//把bodyString转换为NSData数据
NSURL *serverUrl = [[NSURL URLWithString:RequestUrl] URLByAppendingPathComponent:urlStr];//获取到服务器的url地址
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverUrl
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:10];//请求这个地址, timeoutInterval:10 设置为10s超时:请求时间超过10s会被认为连接不上,连接超时
 
[request setHTTPMethod:@"POST"];//POST请求
[request setHTTPBody:bodyData];//body 数据
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];//请求头
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];//异步发送request,成功后会得到服务器返回的数据

设置请求超时时间已经不起作用了,不管是同步还是异步
这个问题只有在3.0以及之后的iOS中才有的,而且只有在当调用了setHTTPBody之后才会出现timeout失效。这个是苹果公司对URL Loading System的在OS3.0中的一个改动,不过在我看来其实这就是一个bug!在setHTTPBody之后,request的timeout会被改为 240s(这个你可以通过[request timeoutInterval]查看),苹果开发人员的解释就是通常我们自己设置的太短的timeout其实是没什么作用的,尤其对移动设备上来讲与网 络沟通需要的时间往往是比较长的,假如你的timeout是10s,在WWAN的网络环境下,可能才刚刚“bring WWAN Interface up”(不知道怎么翻译,囧)。所以自从iOS 3后,如果设置了HTTP body的data,系统就会自动设置一个最低的timeout值,即240s,而且这个值都是不能被改动的,即是你自己再次设置了 timeoutInterval,你通过request timeoutInterval]得到的还是240s!

猜你喜欢

转载自blog.csdn.net/qq_28091923/article/details/86233229