在HTTP帖子连接中实现连接超时(比方说,20秒)的最佳方法是什么?
我目前的代码如下:
-(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 :(得分:1)
请参阅:
NSMutableURLRequest timeout interval not taken into consideration for POST requests
显然会忽略240秒以下的超时。该问题中最高的投票答案与解决方案相关联。但是,我只是建议使用ASIHTTPRequest库。