【发布时间】:2011-09-26 16:40:40
【问题描述】:
在 HTTP post 连接中实现连接超时(比如 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,但是当这 10 秒到来时似乎什么都没有发生。
【问题讨论】:
-
你实现了
NSURLConnection委托方法吗? -
查看委托方法,我没有看到提到超时的方法。连接:didReceiveResponse:,连接:didReceiveData:,连接:didFailWithError:和connectionDidFinishLoading:。
-
嗯,
connection:didFailWithError会在请求超时时被调用 -
看看这个问题,它是关于发布请求stackoverflow.com/questions/2736967/…
-
我很欣赏这个链接。谢谢!
标签: objective-c ios cocoa-touch http-post