【问题标题】:Python, Detect is a URL needs to be HTTPS vs HTTPPython,检测是一个 URL 需要是 HTTPS vs HTTP
【发布时间】:2014-07-09 00:01:07
【问题描述】:

使用python标准库,有没有办法确定给定的网址应该使用HTTP还是HTTPS?如果您使用 HTTP://.com 访问网站,是否有标准错误代码显示 hey dummy 它应该是“HTTPS”而不是 http?

谢谢

【问题讨论】:

    标签: http python-2.7 https urllib2 urllib


    【解决方案1】:

    你做过什么测试吗?

    您的问题的简短回答是: 不存在应该使用...这是您的偏好,或者根本是服务器决定,因为重定向。

    有些服务器确实只允许 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"
    

    【讨论】:

      猜你喜欢
      • 2011-11-04
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多