有人可以告诉我如何使用http.client检查HTTP响应的状态码吗?我没有在http.client的纪录片中找到任何专门的内容。 代码如下:
if conn.getresponse():
return True #Statuscode = 200
else:
return False #Statuscode != 200
我的代码如下:
from urllib.parse import urlparse
import http.client, sys
def check_url(url):
url = urlparse(url)
conn = http.client.HTTPConnection(url.netloc)
conn.request("HEAD", url.path)
r = conn.getresponse()
if r.status == 200:
return True
else:
return False
if __name__ == "__main__":
input_url=input("Enter the website to be checked (beginning with www):")
url = "http://"+input_url
url_https = "https://"+input_url
if check_url(url_https):
print("The entered Website supports HTTPS.")
else:
if check_url(url):
print("The entered Website doesn't support HTTPS, but supports HTTP.")
if check_url(url):
print("The entered Website supports HTTP too.")
答案 0 :(得分:0)
看看documentation here,您只需要这样做:
r = conn.getresponse()
print(r.status, r.reason)
更新:如果您要(如注释中所述)检查http连接,则最终可以使用HTTPConnection
并读取状态:
import http.client
conn = http.client.HTTPConnection("docs.python.org")
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
如果网站已正确配置为实施HTTPS,则您的状态码不应为200;在此示例中,您将收到一个301 Moved Permanently
响应,这意味着请求已重定向,在这种情况下,该请求已重写为HTTPS。