【问题标题】:Find where a t.co link goes to [closed]查找 t.co 链接指向的位置
【发布时间】:2011-09-23 22:48:05
【问题描述】:

给定一个 t.co 链接,我如何找到链接解析的位置?例如,如果我有 t.co/foo,我想要一个返回 domain.com/bar 的函数或进程。

【问题讨论】:

    标签: twitter url-shortener


    【解决方案1】:

    我会远离您无法控制的外部 API。这只会在您的应用程序中引入一个潜在的故障点,并且可能会花钱使用。

    CURL 可以很好地做到这一点。下面是我在 PHP 中的做法:

    function unshorten_url($url) {
      $ch = curl_init($url);
      curl_setopt_array($ch, array(
        CURLOPT_FOLLOWLOCATION => TRUE,  // the magic sauce
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_SSL_VERIFYHOST => FALSE, // suppress certain SSL errors
        CURLOPT_SSL_VERIFYPEER => FALSE, 
      ));
      curl_exec($ch); 
      return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    }
    

    我确信这可以适应其他语言,甚至可以在 UNIXy 系统上使用 curl 命令编写脚本。

    http://jonathonhill.net/2012-05-18/unshorten-urls-with-php-and-curl/

    【讨论】:

    • 不错的解决方案。我是否可以建议设置 CURLOPT_NOBODY => true 以便执行 HEAD 请求并且实际上并未获取最终资源?
    【解决方案2】:

    curl -s -o /dev/null --head -w "%{url_effective}\n" -L "https://t.co/6e7LFNBv"

    • --head-I 仅下载 HTTP 标头
    • -w--write-out 在输出后打印指定字符串
    • -L--location 跟随位置标题

    【讨论】:

    • 我喜欢这个解决方案。它只输出 URL(因此不需要进一步解析)并且它遵循多个重定向。实际上,它与命令行中 PHP 中的解决方案相同,对吧? stackoverflow.com/a/10661246/2444812
    【解决方案3】:

    如果您想从命令行执行此操作,curl 的详细选项会派上用场:

    curl -v <url>
    

    为您提供 HTTP 回复。对于 t.co,它似乎会给您一个 HTTP/301 回复(永久移动)。然后,有一个 Location 字段,它指向缩短后的 URL。

    【讨论】:

    • 为什么要使用-v?它输出一大堆你不需要的信息。 curl -I (大写 i) 就足够了。
    • 此解决方案不遵循多个重定向。其他一些解决方案可以,例如stackoverflow.com/a/11326239/2444812
    【解决方案4】:

    这是一个 Python 解决方案。

    import urllib2
    
    class HeadRequest(urllib2.Request):
        def get_method(self): return "HEAD"
    
    def get_real(url):
        res = urllib2.urlopen(HeadRequest(url))
        return res.geturl()
    

    使用实际的 twitter t.co 链接进行测试:

    url = "http://t.co/yla4TZys"
    expanded = get_real(url)
    

    扩展 = http://twitter.com/shanselman/status/276958062156320768/photo/1

    用 try-except 结束它,然后你就可以开始了。

    【讨论】:

    • 它不适用于http://t.co/OFlTpTzCqt.throws HTTPError: HTTP Error 303: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: See Other
    【解决方案5】:

    另一个 Python 解决方案,这一次依赖于 requests 模块而不是 urllib2(以及所有其他库):

    #!/usr/bin/env python
    
    import requests
    
    shorturl = raw_input("Enter the shortened URL in its entirety: ")
    r = requests.get(shorturl)
    
    print("""
    The shortened URL forwards to:
    
        %s
    """ % r.url)
    

    【讨论】:

    • 更好的是,仅使用以下命令下载标头:r = requests.head(shorturl, allow_redirects=True)
    【解决方案6】:

    这是一个 R 解决方案,从该线程中的其他答案以及 RCurl 包的example() 代码移植而来:

    unshorten_url <- function(uri){
            require(RCurl)
            if(RCurl::url.exists(uri)){
                    # listCurlOptions()
                    opts <- list(
                            followlocation = TRUE,  # resolve redirects
                            ssl.verifyhost = FALSE, # suppress certain SSL errors
                            ssl.verifypeer = FALSE, 
                            nobody = TRUE, # perform HEAD request
                            verbose = FALSE
                    );
                    curlhandle = getCurlHandle(.opts = opts)
                    getURL(uri, curl = curlhandle)
                    info <- getCurlInfo(curlhandle)
                    rm(curlhandle)  # release the curlhandle!
                    info$effective.url
            } else {
                    # just return the url as-is
                    uri
            }
    }
    

    【讨论】:

      【解决方案7】:

      你可以试试这个 Java 代码。这是使用 java 拥有的 HttpURLConnection 的代码。 : http://www.srccodes.com/p/article/37/expand-shortened-link-using-java?fb_action_ids=1544985322486585&fb_action_types=og.likes

      此 URL 扩展器将如何工作? 将 HttpURLConnection 设置为缩短的 url(比如http://goo.gl/WT6eFw)。

      提取 HTTP 标头字段“Location”的值。而这个值只不过是扩展的或实际的目标 URL。

      关闭连接。

      【讨论】:

        【解决方案8】:

        Twitter 扩展 URL。假设您有一条使用 twitter API 的推文 编码为 json 文件。

        import json
        urlInfo=[]
        
        tweet=json.loads(tweet)
        keyList=tweet.keys() # list of all posssible keys
        tweet['entities'] # gives us values linked to entities 
        

        您可以观察到有一个名为 'urls' 的值 tweet['entities']['urls'] # 给出映射到键 url 的值

        urlInfo=tweet['entities']['expanded_url'] # move it to a list
        # iterating over the list.. gives shortened URL
        # and expanded URL
        for item in urlInfo:
          if "url" and "expanded_url" in urlInfo.keys():
            print(item["url"] + " "+item["expanded_url"])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-19
          • 1970-01-01
          • 1970-01-01
          • 2013-02-08
          • 1970-01-01
          • 2010-12-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多