python-3.xhttp.client

Encountered the error when using HTTP client library in Python


I'm using the HTTP client library to send a RESTful GET to a server. This is my code:

import http.client
conn = http.client.HTTPSConnection("")
headers = { 'authorization': "Bearer eyJ0eXAiOiJKV1QiLCJhbG.....JNa0UyT" }
conn.request("GET", "https://xxxx-xxxx.auth0.com/api/v2/jobs/job_xxxxxx", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

And this is an error:

Traceback (most recent call last):
  File "getResult.py", line 4, in <module>
    conn.request("GET", "https://xxxxxx.auth0.com/api/v2/jobs/job_xxxxxx", headers=headers)
  File "/usr/lib/python3.5/http/client.py", line 1106, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request
    self.endheaders(body)
  File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
    self.send(msg)
  File "/usr/lib/python3.5/http/client.py", line 877, in send
    self.connect()
  File "/usr/lib/python3.5/http/client.py", line 1252, in connect
    super().connect()
  File "/usr/lib/python3.5/http/client.py", line 849, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/usr/lib/python3.5/socket.py", line 693, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/lib/python3.5/socket.py", line 732, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

I don't know why. Could I have a help?


Solution

  • Looking at the official docs, you should instantiate the connection with the hostname and port, and then perform the GET only with the endpoint string. You are actually asking the server "" the resource "https://xxxx-xxxx.auth0.com/api/v2/jobs/job_xxxxxx"

    Examples

    conn = http.client.HTTPSConnection("https://xxxx-xxxx.auth0.com")
    headers = { 'authorization': "Bearer eyJ0eXAiOiJKV1QiLCJhbG.....JNa0UyT" }
    conn.request("GET", "/api/v2/jobs/job_xxxxxx", headers=headers)
    

    Anyway, I suggest you to use requests for making HTTP calls. It's the de facto library in this context.