在 iOS 后重试 HTTP 请求

Retry a HTTP request in iOS

我正在使用 NSURLConnection 发送 HTTP 请求,运行 [[NSURLConnection 分配] 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];

}

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

来电者:

[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 {
        }

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

如果您不想这样做,则需要保存参数和 URL,然后重试,也许在 connectionDidFinishLoading:.

尽管如此,我正在尝试想象您想要重试 4xx HTTP 错误的场景。似乎更有可能出现连接错误,因此您将其放在 connection:didFailWithError.

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

这是伪代码:

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

//调用加载请求的函数

}

我会向您推荐STNetTaskQueue,因为它提供了每个网络任务的重试时间和重试间隔。

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