将HTTP
HEAD请求发送到URL并查看响应代码。如果代码是30x,请查看
Location标题以获取未缩短的URL。否则,如果代码是20x,则不会重定向URL;否则,URL不会重定向。您可能还希望以某种方式处理错误代码(4xx和5xx)。例如:
# This is for Py2k. For Py3k, use http.client and urllib.parse instead, and# use // instead of / for the divisionimport httplibimport urlparsedef 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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)