HTTPS request in Python

后端 未结 2 429
耶瑟儿~
耶瑟儿~ 2020-12-31 06:10

I would like to connect to a site via HTTPS in Python 3.2.

I tried

    conn = http.client.HTTPSConnection(urlStr, 8443)
    conn.putrequest(\'GET\',          


        
相关标签:
2条回答
  • 2020-12-31 06:15

    First of all, if you just want to download something and don't want any special HTTP requests, you should use urllib.request instead of http.client.

    import urllib.request
    r = urllib.request.urlopen('https://paypal.com/')
    print(r.read())
    

    If you really want to use http.client, you must call endheaders after you send the request headers:

    import http.client
    conn = http.client.HTTPSConnection('paypal.com', 443)
    conn.putrequest('GET', '/')
    conn.endheaders() # <---
    r = conn.getresponse()
    print(r.read())
    

    As a shortcut to putrequest/endheaders, you can also use the request method, like this:

    import http.client
    conn = http.client.HTTPSConnection('paypal.com', 443)
    conn.request('GET', '/') # <---
    r = conn.getresponse()
    print(r.read())
    
    0 讨论(0)
  • 2020-12-31 06:35

    instead of putrequest, you can use request

    conn.request('GET', '/')
    resp = conn.getresponse()
    print(resp.read())
    
    0 讨论(0)
提交回复
热议问题