LoginSignup
0
0

More than 3 years have passed since last update.

urllib.request

Posted at
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:
#バイナリで返ってくるのでデコードし、jsonから辞書型に変換
    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')))

出力:

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'}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0