import json
import urllib.error
import urllib.request
try:
data = json.dumps({'key':'value'}).encode()
headers = {'Content-Type': 'application/json'}
req = urllib.request.Request(
"http://localhost:8000/",
data=data,
headers=headers,
method="POST"
)
with urllib.request.urlopen(req) as resp:
print(resp.status)
print(resp.headers)
print(resp.read())
except urllib.error.HTTPError as e:
print("HTTPError", e)
print(e.status)
print(e.headers)
print(e.read())
except urllib.error.URLError as e:
print("URLError", e)
print(e.reason)
except e:
print(e)
参考