我正在使用 NSURLConnection 发送 HTTP 请求并运行它 [[NSURLConnection alloc] initWithRequest:request delegate:self]; 其中“请求”是一个已配置的 NSMutableURLRequest 对象。基于错误代码(404 或 500)的 HTTP 错误,我想重试请求。
我在“connection: didReceiveResponse”委托(delegate)方法中得到错误响应和 HTTP 状态代码。我应该如何实现重试请求?
提前致谢!
P.S:我尝试取消连接并在收到错误时启动它,但它没有任何效果,因为 NSURLConnection 在完成加载或取消后释放委托(delegate)。
-----更新-----
-(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];
}
在我的模型类中,我有调用者方法和委托(delegate)
来电者:
[MyModel doHTTPGet:url delegate:self timeout:HTTP_TIMEOUT];
委托(delegate)方法:
- (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
功能包装在另一个类中(在我的例子中,称为 APIGetter),它有自己的委托(delegate)协议(protocol)和方法,并处理诸如重试之类的事情。
如果您不想这样做,则需要保存参数和 URL,然后重试,也许在 connectionDidFinishLoading:
中。
尽管如此,我正在尝试想象一个场景,您想要重试 4xx
HTTP 错误。似乎更有可能出现连接错误,因此您将其放在 connection:didFailWithError
中。
关于ios - 在 iOS 中重试 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950897/