objective-c - 在 Cocoa 中获取缩短 URL 的长 URL 的最简单方法?

在 Cocoa 中检索短 URL 的原始 URL 的最简单方法是什么?几行就可以搞定什么?

最佳答案

更新:我刚刚看到您的评论,并意识到它正在跟踪重定向。

查看委托(delegate)方法:connection:willSendRequest:redirectResponse:,它告诉您它正在根据之前的响应重定向到这个新请求。

您可以从此处的新请求或重定向响应的 Location header 中获取展开后的 URL。

Discussion If the delegate wishes to cancel the redirect, it should call the connection object’s cancel method. Alternatively, the delegate method can return nil to cancel the redirect, and the connection will continue to process. This has special relevance in the case where redirectResponse is not nil. In this case, any data that is loaded for the connection will be sent to the delegate, and the delegate will receive a connectionDidFinishLoading or connection:didFailLoadingWithError: message, as appropriate.

原始答案如下...

NSURLConnection 与委托(delegate)一起使用。在您的委托(delegate)的 connection:didReceiveResponse: 方法中,获取 allHeaderFields 并读取“Location” header 的值。

类似:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"Expanded URL = %@", [[(NSHTTPURLResponse *)response allHeaderFields] objectForKey:@"Location"]);
}

我会创建一个小的 URLExpander 类来亲自执行此操作,其签名类似于:

+(void)asyncExpandURL:(NSURL *)aURL didExpandTarget:(id)target selector:(SEL)selector;

然后在您的消息中传回两个参数,一个用于短 URL,一个用于长 URL。

https://stackoverflow.com/questions/4480903/

相关文章:

url - 是否有用于将短网址翻译回常规链接的 API?

url - 谷歌短网址如何运作?

php - 如何用 PHP 中的 goo.gl 等短 URL 识别域名?

apache - 无法让 mod_rewrite 正确(且不可见地)重写我的 URL?

url - 短网址冲突。更喜欢项目还是项目列表?

apache - mod_rewrite 制作短网址

regex - 解析短网址的正则表达式

php - PHP 和 MySQL 中的短 URL 出站链接跟踪

javascript - 使用 JSON 使用 Javascript 缩短 URL

php - 修改 url 更短的脚本