(Python) 如何检查 http 响应状态

QWE*_*XCV -2 python http response status

有人可以告诉我如何使用 http.client 检查 HTTP 响应的状态码吗?我在 http.client 的纪录片中没有找到任何具体内容。代码如下所示:

  if conn.getresponse():
    return True #Statuscode = 200
  else:
    return False #Statuscode != 200
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像这样:

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.")
Run Code Online (Sandbox Code Playgroud)

oli*_*x14 5

看看这里的文档,你只需要做:

r = conn.getresponse()
print(r.status, r.reason)
Run Code Online (Sandbox Code Playgroud)

更新:如果您想(如评论中所述)检查 http 连接,您最终可以使用HTTPConnection并读取状态:

import http.client

conn = http.client.HTTPConnection("docs.python.org")
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
Run Code Online (Sandbox Code Playgroud)

如果网站正确配置为实施 HTTPS,则状态代码不应为 200;在此示例中,您将收到301 Moved Permanently响应,这意味着请求已重定向,在本例中重写为 HTTPS 。