首页 文章

在iOS中重试HTTP请求

提问于
浏览
1

我正在使用NSURLConnection发送HTTP请求并使用[[NSURLConnection alloc] initWithRequest运行它:request delegate:self];其中“request”是配置的NSMutableURLRequest对象 . 在基于错误代码(404或500)的HTTP错误时,我想重试该请求 .

我在“connection:didReceiveResponse”委托方法中获得了错误响应和HTTP状态代码 . 我该如何实现重试请求?

提前致谢!

P.S:我尝试取消连接并在收到错误时启动它,但它没有任何效果,因为NSURLConnection在完成加载或取消后释放了委托 .

----- -----更新

-(void)doHTTPGet:(NSString *)url delegate:(id  <NSURLConnectionDelegate>)delegate timeout:(NSTimeInterval)timeout
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:timeout];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    // send request by instanciating NSURLConnection
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:delegate];

}

在我的模型类中,我有调用方法和委托

呼叫者:

[MyModel doHTTPGet:url delegate:self timeout:HTTP_TIMEOUT];

代表方法:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    httpResponseStatusCode = [httpResponse statusCode];
    DLOG(@"HTTP status code=%ld", (long)httpResponseStatusCode);

    if (httpResponseStatusCode == 404)
    {
       // RETRY HERE
    } 
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [httpResponseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    // some code PROCESSING RESPONSE
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        }

3 回答

  • 1

    在您的响应中,只需使用switch或if语句来检查您希望的错误,如果您的响应是404或500,则重新加载请求

    这是伪代码:

    如果错误包含字符串(404或500){

    //调用加载请求的函数

    }

  • 0

    我建议您使用STNetTaskQueue,因为它为每个网络任务提供重试时间和重试间隔 .

    更重要的是,它可以自动从请求对象中打包请求参数,并且最大并发网络任务也是可配置的 .

  • 0

    我将 NSURLConnection 功能包装在另一个类(在我的例子中称为APIGetter)中,它有自己的委托协议和方法,并处理重试之类的事情 .

    如果您不需要保存参数和URL,请重试,也许在 connectionDidFinishLoading: 中 .

    虽然,我想重试 4xx HTTP错误 . 似乎更有可能出现连接错误,所以你要把它放在 connection:didFailWithError 中 .

相关问题