I have a problem with the urllib
library in Python 3.
This is my code:
!/usr/bin/python3
import http.client
import urllib.request
import urllib.parse
import time
from datetime import datetime
import json
device = "[email protected]"
api_key = ""
api_url = "http://api.carriots.com/devices"
#Parameters - Body
timestamp = int(time.time())
params = {"order": -1}
binary_data = json.dumps(params).encode('ascii')
#Header
header = { "User-Agent": "raspberrycarriots",
"Content-Type": "application/json",
"carriots.apikey": api_key}
#Request
req= urllib.request.Request(api_url, binary_data, header)
print(req)
f = urllib.request.urlopen(req)
#Print response
print(f.read().decode('utf-8'))
This is the answer that I got:
urllib.request.Request object at 0x74cd2370>
Traceback (most recent call last):
File "/usr/lib/python3.4/urllib/request.py", line 1174, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "/usr/lib/python3.4/http/client.py", line 1090, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python3.4/http/client.py", line 1128, in _send_request
self.endheaders(body)
File "/usr/lib/python3.4/http/client.py", line 1086, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.4/http/client.py", line 924, in _send_output
self.send(msg)
File "/usr/lib/python3.4/http/client.py", line 859, in send
self.connect()
File "/usr/lib/python3.4/http/client.py", line 836, in connect
self.timeout, self.source_address)
File "/usr/lib/python3.4/socket.py", line 491, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/lib/python3.4/socket.py", line 530, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/Documents/Python Programs/demoget.py", line 31, in <module>
f = urllib.request.urlopen(req)
File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.4/urllib/request.py", line 455, in open
response = self._open(req, data)
File "/usr/lib/python3.4/urllib/request.py", line 473, in _open
'_open', req)
File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
result = func(*args)
File "/usr/lib/python3.4/urllib/request.py", line 1202, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "/usr/lib/python3.4/urllib/request.py", line 1176, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
I hope you can help me.