且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何取消缩短网址?

更新时间:2023-11-26 20:34:46

向 URL 发送 HTTP HEAD 请求并查看响应代码.如果代码是 30x,请查看 Location 标头以获取未缩短的 URL.否则,如果代码为20x,则不重定向URL;您可能还想以某种方式处理错误代码(4xx 和 5xx).例如:

Send an HTTP HEAD request to the URL and look at the response code. If the code is 30x, look at the Location header to get the unshortened URL. Otherwise, if the code is 20x, then the URL is not redirected; you probably also want to handle error codes (4xx and 5xx) in some fashion. For example:

# This is for Py2k.  For Py3k, use http.client and urllib.parse instead, and
# use // instead of / for the division
import httplib
import urlparse

def unshorten_url(url):
    parsed = urlparse.urlparse(url)
    h = httplib.HTTPConnection(parsed.netloc)
    h.request('HEAD', parsed.path)
    response = h.getresponse()
    if response.status/100 == 3 and response.getheader('Location'):
        return response.getheader('Location')
    else:
        return url