现在的位置: 首页 > 综合 > 正文

设置请求超时的时间

2017年12月08日 ⁄ 综合 ⁄ 共 1885字 ⁄ 字号 评论关闭
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    

    NSLog( @"this is First in viewDidLoad" );

    int defaultTimeout = 3.0f;
    NSString *str = @"http://www.baidu.com";
    NSURL *url = [NSURL URLWithString: str];
    NSString *outputBody = @"yes";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                       timeoutInterval:defaultTimeout];
    NSData *bodyData = [outputBody dataUsingEncoding:NSUTF8StringEncoding];
    
    NSArray *cookies = [NSArray array];
    if(cookies != nil) {
        [request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:cookies]];
    }
    [request setValue:@"wsdl2objc" forHTTPHeaderField:@"User-Agent"];
    [request setValue:@"soapAction" forHTTPHeaderField:@"SOAPAction"];
    [request setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%u", [bodyData length]] forHTTPHeaderField:@"Content-Length"];
    [request setValue: str forHTTPHeaderField:@"Host"];
    [request setHTTPMethod: @"POST"];
    
    [request setHTTPBody: bodyData];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:nil];
    
    //自定义时间超时
    [NSTimer scheduledTimerWithTimeInterval:defaultTimeout 
                                     target: self 
                                   selector: @selector(handleTimer) 
                                   userInfo:nil 
                                    repeats:NO];
    
    
    [connection release];
}


//时间超时定义
-(void) handleTimer
{
    //请求超时后,要执行的操作,比如:退出,弹出提示等。。。
    NSLog( @"超时了,推出程序" );
}

There's a thread on Apple dev forums discussing this issue. Apparently on iPhone OS, the setter mandates timeoutInterval a minimum of 240 seconds
(4 minutes). This only occurs when the postBody is not empty (typically when using a POST request). This seems crazy, but apparently it's there to make sure requests leave the system even though it might take many seconds for the WWAN (3G) interface to wake
up. 240 seconds seems rather steep, so they suggest to set a timer and cancel the asynchronous connection when your timer fires. I know this seems stupid, but that's the only I managed to get timeout for POST requests... :-(

抱歉!评论已关闭.