【问题标题】:iPhone NSURL get last redirected urliPhone NSURL 获取最后一个重定向的 url
【发布时间】:2010-12-29 11:05:25
【问题描述】:

我想知道如何将您的 NSURL 更新为您的网址将重定向到的最后一个网址
使用 NSURL 或 NSRequest

感谢您的帮助。 谢谢。

【问题讨论】:

    标签: iphone url redirect


    【解决方案1】:

    只有在尝试使用 NSURLConnection 进行连接后才能发现这一点。如果你向你的 NSURLConnection 委托添加一个方法,-connection:willSendRequest:redirectResponse:,你会在重定向发生之前得到通知。只需从传递的请求中获取 URL,这就是您的答案。

    【讨论】:

    • 我不这么认为。 Apple 不鼓励同步操作。
    【解决方案2】:

    我做到了,

    方法如下

    NSURL *originalUrl=[NSURL URLWithString:@"http://YourURL.com"];
    NSData *data=nil;  
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:originalUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    NSURLResponse *response;
    NSError *error;
    data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSURL *LastURL=[response URL];
    [request release];
    [error release];
    

    【讨论】:

      【解决方案3】:

      zanque 的解决方案有效,但为了避免下载“无用”数据,我将 http 方法更改为 HEAD :

      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:orinigalURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0];
      [request setHTTPMethod:@"HEAD"];
      NSURLResponse *response = nil;
      [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
      NSURL *finalURL = response.URL;
      

      【讨论】:

      • 这可能更适合作为评论而不是答案。或者也许是一个编辑。
      • @EWit,该用户有 1 个代表。他们无法发表评论。此外,这为问题提供了另一种答案。
      • @Andy 我刚刚发表了一条评论,旨在提供一些未来的指导。但是因为它扩展了现有答案,所以最好将其作为答案的编辑,以便阅读它的人同时了解问题和解决方案。还有一个原因我选择使用“可能”而不是“应该”。
      【解决方案4】:

      您使用以下 swift 代码获取最终重定向的 url:

                  let request = NSMutableURLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 15.0)
              request.httpMethod = "HEAD"
              var response: URLResponse? = nil
              do {
                  try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: &response)
              } catch { //Handle exception //if any
              }
              let finalURL = response?.url
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-21
        • 2014-01-02
        • 1970-01-01
        • 2011-03-05
        • 2019-10-30
        • 2019-12-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多