Objective c 在HTTP Post中实现超时
在HTTP post连接中实现连接超时(比如20秒)的最佳方法是什么 我目前的代码如下:Objective c 在HTTP Post中实现超时,objective-c,ios,cocoa-touch,http-post,Objective C,Ios,Cocoa Touch,Http Post,在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 = [postStrin
-(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秒达到时,似乎什么也没有发生。请参阅:
显然,240秒以下的超时被忽略。该问题投票率最高的答案与解决方案相关。但是,我只建议改用ASIHTTPRequest库
参见:
显然,240秒以下的超时被忽略。该问题投票率最高的答案与解决方案相关。但是,我只建议改用ASIHTTPRequest库
您是否实现了
NSURLConnection
委托方法?查看委托方法,我没有看到提到超时的方法。connection:didReceiveResponse:,connection:didReceiveData:,connection:didFailWithError:和ConnectiondFinishLoading:。嗯,connection:didFailWithError
将在请求到达超时时被调用。不过,请看一下这个问题,这是关于post请求的。我很欣赏这个链接。非常感谢。您是否实现了NSURLConnection
delegate方法?通过查看delegate方法,我没有看到提到超时的方法。connection:didReceiveResponse:,connection:didReceiveData:,connection:didFailWithError:和ConnectiondFinishLoading:。嗯,connection:didFailWithError
将在请求到达超时时被调用。不过,请看一下这个问题,这是关于post请求的。我很欣赏这个链接。非常感谢。然而,通过查看苹果的文档,他们在示例代码中使用了60的超时。我很困惑,但是通过查看苹果的文档,他们在示例代码中使用了60的超时。我很困惑。