2011-09-26 68 views
1

在HTTP post连接中实现连接超时(比方说,20秒)的最佳方式是什么?在HTTP中实现超时

我当前的代码如下:

-(NSData*) postData: (NSString*) strData 
{  
    //postString is the STRING TO BE POSTED 
    NSString *postString; 

    //this is the string to send 
    postString = @"data="; 
    postString = [postString stringByAppendingString:strData]; 

    NSURL *url = [NSURL URLWithString:@"MYSERVERHERE"]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]]; 

    //setting prarameters of the POST connection 
    [request setHTTPMethod:@"POST"]; 
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 
    [request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"]; 
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 
    [request setTimeoutInterval:10.0]; 

    NSLog(@"%@",postString); 

    NSURLResponse *response; 
    NSError *error; 

    NSLog(@"Starting the send!"); 
    //this sends the information away. everybody wave! 
    NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"Just finished receiving!"); 
    if (&error) //OR TIMEOUT 
    { 
     NSLog(@"ERROR!"); 
     NSString *errorString = [NSString stringWithFormat:@"ERROR"]; 
     urlData = [errorString dataUsingEncoding:NSUTF8StringEncoding]; 
    } 
    return urlData; 
} 

显然超时间隔设置为10.0,但似乎没有任何当这十秒不发生。

+0

您是否实现了'NSURLConnection'委托方法? –

+0

不,我没有。 – Baub

+0

查看委托方法,我没有看到提到超时的情况。连接:didReceiveResponse :,连接:didReceiveData:,连接:didFailWithError:和connectionDidFinishLoading :. – Baub

回答