开发者

Implement Timeout in HTTP Post

What is the best way to implement a connection timeout (let's say, 20 seconds) within an HTTP post connection?

My current code is as follows:

-(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;
}

Obviously the timeout interval is set to 10.0, but nothing seems to happen when those ten seconds hit.


See:

NSMutableURLRequest timeout interval not taken into consideration for POST requests

Apparently timeouts under 240 seconds are ignored. The highest voted answer in that question links to a solution. However, I would simply recommend using the ASIHTTPRequest library instead.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜