4

通过阅读文档NSURLConnection,该currentRequest方法应该反映加载时可能发生的任何重定向:

当连接执行负载时,请求可能会由于协议规范化或由于以下重定向而改变。此方法用于检索当前值。

但是,当我检查它时currentRequestconnectionDidFinishLoading:它总是有原始请求的 URL,即使检查响应数据表明重定向成功完成。(请参见下面的人为示例)

我的问题是:为什么不currentRequest返回实际的当前请求?我做错了什么还是这是预期的行为?如果这预期的行为,那么currentRequest应该有什么用处?

@interface AppDelegate : UIResponder <UIApplicationDelegate, NSURLConnectionDataDelegate>
@property (strong, nonatomic) NSURLConnection *connection;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSURL *url = [[NSURL alloc] initWithString:@"http://jigsaw.w3.org/HTTP/300/301.html"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    return YES;
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    NSLog(@"willSendRequest // request: %@ // currentRequest: %@", request, [connection currentRequest]);
    return request;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"didFinishLoading // originalRequest: %@ // currentRequest: %@", [connection originalRequest], [connection currentRequest]);
}

@end

运行这个例子会给我以下输出:

2012-12-18 15:18:44.949 ConnectionTest[12534:c07] willSendRequest // request: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html> // currentRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html>
2012-12-18 15:18:44.954 ConnectionTest[12534:c07] willSendRequest // request: <NSURLRequest http://jigsaw.w3.org/HTTP/300/Overview.html> // currentRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html>
2012-12-18 15:18:44.955 ConnectionTest[12534:c07] didFinishLoading // originalRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html> // currentRequest: <NSURLRequest http://jigsaw.w3.org/HTTP/300/301.html>

我的期望是最后一次调用currentRequest会显示以 结尾的页面 URL Overview.html,但它仍然显示301.html

4

3 回答 3

3

我只是将这归结为 Apple 不得不混淆文档。我可以通过检查响应对象来获得最终的请求 URL,但对我来说,所谓的东西currentRequest应该反映在重定向之后发出的最后一个请求。

于 2012-12-30T20:20:49.630 回答
2

重定向是如何发生的?http 服务器是否返回重定向状态?

原始 URL 请求可能不是可变的,因此系统无法修改 URL。

您必须为每个重定向发出一个新请求,如此处的答案所述:使用 NSURLConnection 正确处理重定向

您不是从连接中获取最终 URL,而是从响应对象中获取。例如,请参阅我制作的这个 URL unshortener:http: //www.cocoanetics.com/2012/06/mine-is-longer-than-yours/

于 2012-12-30T09:10:53.490 回答
0

我不是 Iphone Developper(只是 Mac),但似乎大多数 NSURLConnectionDelegate 方法在 iOS5 中已被弃用,而 NSURLDownload (及其委托)似乎是执行此操作的新方法:NSURLConnectionDelegate NSURLDownloadDelegate

于 2012-12-19T05:50:01.253 回答