[PYTHON] urllib.request

import urllib.request
import json

payload = {'key1': 'value1', 'key2': 'value2'}

url = 'http://httpbin.org/get'+ '?' + urllib.parse.urlencode(payload)
print(url)
with urllib.request.urlopen(url) as f:
#Since it is returned in binary, decode it and convert from json to dictionary type
    print(json.loads(f.read().decode('utf-8')))

payload = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(
    'http://httpbin.org/post', data=payload, method='POST')
with urllib.request.urlopen(req) as f:
    print(json.loads(f.read().decode('utf-8')))

req = urllib.request.Request(
    'http://httpbin.org/put', data=payload, method='PUT')
with urllib.request.urlopen(req) as f:
    print(json.loads(f.read().decode('utf-8')))

req = urllib.request.Request(
    'http://httpbin.org/delete', data=payload, method='DELETE')
with urllib.request.urlopen(req) as f:
    print(json.loads(f.read().decode('utf-8')))

output:

http://httpbin.org/get?key1=value1&key2=value2
{'args': {'key1': 'value1', 'key2': 'value2'}, 'headers': {'Accept-Encoding': 'identity', 'Host': 'httpbin.org', 'User-Agent': 'Python-urllib/3.7', 'X-Amzn-Trace-Id': 'Root=1-5e681895-882b69b4d459c90c94c8b1f4'}, 'origin': '118.158.151.210', 'url': 'http://httpbin.org/get?key1=value1&key2=value2'}
{'args': {}, 'data': '', 'files': {}, 'form': {'{"key1": "value1", "key2": "value2"}': ''}, 'headers': {'Accept-Encoding': 'identity', 'Content-Length': '36', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'Python-urllib/3.7', 'X-Amzn-Trace-Id': 'Root=1-5e681895-8ec97c2f22fbed1d1dfe27c6'}, 'json': None, 'origin': '118.158.151.210', 'url': 'http://httpbin.org/post'}
{'args': {}, 'data': '', 'files': {}, 'form': {'{"key1": "value1", "key2": "value2"}': ''}, 'headers': {'Accept-Encoding': 'identity', 'Content-Length': '36', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'Python-urllib/3.7', 'X-Amzn-Trace-Id': 'Root=1-5e681895-034fdaec2f567cc8ce08b10f'}, 'json': None, 'origin': '118.158.151.210', 'url': 'http://httpbin.org/put'}
{'args': {}, 'data': '', 'files': {}, 'form': {'{"key1": "value1", "key2": "value2"}': ''}, 'headers': {'Accept-Encoding': 'identity', 'Content-Length': '36', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'Python-urllib/3.7', 'X-Amzn-Trace-Id': 'Root=1-5e681896-2b40064de4e8f1e24e881d8d'}, 'json': None, 'origin': '118.158.151.210', 'url': 'http://httpbin.org/delete'}

Recommended Posts

urllib.request
fixture of urllib.request
Proxy settings for urllib.request