Python,Detect是一个需要HTTPS和HTTP的URL [英] Python, Detect is a URL needs to be HTTPS vs HTTP

查看:386
本文介绍了Python,Detect是一个需要HTTPS和HTTP的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python标准库,有没有办法确定给定的Web地址是使用HTTP还是HTTPS?如果你使用HTTP点击网站://.com是否有一个标准的错误代码,说它是虚拟的,它应该是'HTTPS'而不是http?

Using the python standard library, is there a way to determine if a given web address should use HTTP or HTTPS? If you hit a site using HTTP://.com is there a standard error code that says hey dummy it should be 'HTTPS' not http?

谢谢你

推荐答案

你做过任何类型的测试吗?

Did u make any sort of testing?

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

The short, prematural answer of your questions is: Does not exist should use... it's your preference, or a server decision at all, because of redirects.

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

Some servers does allow only https, and when you call http does return 302 code.

所以,如果你的目标是从给定的URL加载https ,只需尝试回退到正常的http。

So, if you goal is to load https from a given url, just try it with a fallback to normal http.

我建议你只发送HEAD请求,这样你就可以非常快速地识别出https连接是否正在收听。我不建议您检查端口443(ssl),因为有时人们不遵守该规则,https协议将确保您处于https而不是假443端口。

I've recommend you to send only HEAD requests, so you can recognize very fast if the https connection is being listening or not. I do not recommend you to check for port 443 (ssl) because sometimes people do not follow that rule and https protocol will ensure that you is under https and not under a fake 443 port.

一些代码:

#!/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"

这篇关于Python,Detect是一个需要HTTPS和HTTP的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆