Skip to content

Instantly share code, notes, and snippets.

@abitrolly
Last active July 12, 2024 03:11
Show Gist options
  • Save abitrolly/7cee9d2054a9bff715b86f0016e58e72 to your computer and use it in GitHub Desktop.
Save abitrolly/7cee9d2054a9bff715b86f0016e58e72 to your computer and use it in GitHub Desktop.
POST JSON with Python3 urllib
# Public domain
from urllib import request
def post_data(url, data, headers={'Content-Type':'application/json'}):
"""
POST data string to `url`, return page and headers
"""
# if data is not in bytes, convert to it to utf-8 bytes
bindata = data if type(data) == bytes else data.encode('utf-8')
# need Request to pass headers
req = request.Request(url, bindata, headers)
resp = request.urlopen(req)
return resp.read(), resp.getheaders()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment