【问题标题】:Implement Timeout in HTTP Post在 HTTP Post 中实现超时
【发布时间】: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


【解决方案1】:

见:

NSMutableURLRequest timeout interval not taken into consideration for POST requests

显然低于 240 秒的超时将被忽略。该问题中投票最高的答案链接到解决方案。但是,我只是推荐使用 ASIHTTPRequest 库。

http://allseeing-i.com/ASIHTTPRequest/

【讨论】:

  • 然而查看 Apple 的文档,在他们的示例代码中,他们使用了 60 的超时时间。我很困惑。
猜你喜欢
  • 1970-01-01
  • 2016-06-27
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多