获取iOS 5中的最后一个重定向URL?

问题描述 投票:2回答:2

有人可以发布最简单的工作代码,当我GET请求一个URL时,它可以获取最后重定向的URL(nth)吗?

我知道我需要使用异步请求,但是我无法制定出完整的工作代码来解决问题。

我正在使用ios5,因此可以在ios5中使用最新添加的异步内置功能。

我尝试了很多事情,但仍然没有成功。使用下面的代码,我试图发送带有参数的get请求,但是由于站点的重定向,这些参数由于某种原因而丢失了:(!

NSURLRequest *request = [NSURLRequest requestWithURL:urlOriginal];

[NSURLConnection 
sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
{
    NSLog("the returned data should be the final data of the redirected url with parameters but it is not");
}];

}

编辑

所以这就是我现在要做的:

NSURLRequest *requestOriginal = [NSURLRequest requestWithURL:urlOriginal];

 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:requestOriginal delegate:self];

[connection start];

和代表:

-(NSURLRequest *)connection:(NSURLConnection *)connection
        willSendRequest:(NSURLRequest *)request
       redirectResponse:(NSURLResponse *)redirectResponse
{

    if (redirectResponse) {
    NSMutableURLRequest *r = [request mutableCopy]; // original request
    [r setURL: [request URL]];
    return r;
} else {
     NSLog(@"redirecting to : %@", [request URL]);
    return request;
}
}

并且日志为我提供了我所需的正确请求URL以及最初传递的get参数。

现在如何从此请求中获取数据?另一个completionHandler委托方法?

edit2:

好,所以我也实现了其他代理:

  • (无效)连接:(NSURLConnection *)连接didReceiveResponse:(NSURLResponse *)响应

  • (无效)连接:(NSURLConnection *)连接didReceiveData:(NSData *)数据

  • (无效)连接:(NSURLConnection *)连接didFailWithError:(NSError *)错误

  • (void)connectionDidFinishLoading:(NSURLConnection *)connection

objective-c ios web-services ios5
2个回答
1
投票

请阅读文档中的Handling Redirects and Other Request Changes。简要地说,您将需要a)为您的连接提供委托,并且b)在所述委托中实现方法connection:willSendRequest:redirectResponse:。我不确定您要在问题中做什么-您是否只想将连接重定向到的URL中的数据,还是要查看重定向的请求?无论哪种方式,实施上述方法都将有所帮助。您的委托人将能够看到重定向的请求,并且将其返回原样应该会导致连接加载新的URL。


0
投票

我们可以使用NSMutableURLRequest实现。我遵循了这些步骤,对我来说很好。通过下面提到的链接。

URL:Click here: Get the final redirected url

P.S:让我知道是否需要进一步的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.