【发布时间】:2015-11-04 05:13:03
【问题描述】:
我正在使用 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 {
}
【问题讨论】:
标签: ios objective-c asynchronous nsurlconnection