擅长:python、mysql、java
<p>向URL发送HTTP HEAD请求并查看响应代码。如果代码是30x,请查看<code>Location</code>头以获取未排序的URL。否则,如果代码是20x,则不会重定向URL;您可能还希望以某种方式处理错误代码(4xx和5xx)。例如:</p>
<pre><code># 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
</code></pre>