Python,检测URL是否需要使用HTTPS而不是HTTP

9

使用Python标准库,有没有一种方法可以确定给定的Web地址应该使用HTTP还是HTTPS?如果您使用HTTP://.com访问网站,是否有标准错误代码提示“傻瓜应该使用HTTPS而不是http”?

谢谢。

1个回答

6

你是否进行了任何类型的测试?

对于你的问题,简短而言:不存在应该使用...这是你的偏好,或者完全是服务器的决定,因为会发生重定向。

一些服务器只允许使用https,当你调用http时会返回302代码。

所以,如果你的目标是从给定的url加载https,请尝试使用回退到普通的http。

我建议你只发送HEAD请求,这样你就可以很快地识别出https连接是否正在监听。我不建议你检查443端口(ssl),因为有时人们不遵循这个规则,https协议将确保你处于https而不是伪造的443端口。

一些代码:

#!/usr/bin/env python
#! -*- coding: utf-8 -*-

from urlparse import urlparse
import httplib, sys

def check_url(url):
  url = urlparse(url)
  conn = httplib.HTTPConnection(url.netloc)   
  conn.request("HEAD", url.path)
  if conn.getresponse():
    return True
  else:
    return False

if __name__ == "__main__":
  url = "http://httpbin.org"
  url_https = "https://" + url.split("//")[1]
  if check_url(url_https):
    print "Nice, you can load it with https"
  else:
    if check_url(url):
      print "https didn't load, but you can use http"
  if check_url(url):
    print "Nice, it does load with http too"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接