-2

can someone tell me how to check the statuscode of a HTTP response with http.client? I didn't find anything specifically to that in the documentary of http.client. Code would look like this:

  if conn.getresponse():
    return True #Statuscode = 200
  else:
    return False #Statuscode != 200

My code looks like that:

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.")
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
QWERASDFYXCV
  • 245
  • 1
  • 6
  • 15

1 Answers1

4

Take a look at the documentation here, you simply needs to do:

r = conn.getresponse()
print(r.status, r.reason)

Update: If you want (as said in the comments) to check an http connection, you could eventually use an HTTPConnection and read the status:

import http.client

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

If the website is correctly configured to implement HTTPS, you should not have a status code 200; In this example, you'll get a 301 Moved Permanently response, which means the request was redirected, in this case rewritten to HTTPS .

olinox14
  • 6,177
  • 2
  • 22
  • 39
  • Thank you that works, but my intention is to check if the website supports HTTPS and HTTP or only HTTP. But if i test a website which doesn't support HTTPS it still tells me it does support it. Do i check for the wrong statuscode when i check for "200"? – QWERASDFYXCV May 15 '19 at 15:42
  • So for what statuscode i have to check when i want to equal test it? I mean i want to test the website if it works with HTTPS and if yes/no i want to check if it works with HTTP. But with my solution every website supports both, although some entered websites doesn't support HTTPS. Thank you so far :) – QWERASDFYXCV May 15 '19 at 15:56
  • Just send an HTTPSRequest, you should get an Exception (I think a `ConnectionRefusedError`) if the website does not support https... – olinox14 May 16 '19 at 07:16