Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Murthysagi/00f4270acbf68336e1664e35c9d92fb9 to your computer and use it in GitHub Desktop.
Save Murthysagi/00f4270acbf68336e1664e35c9d92fb9 to your computer and use it in GitHub Desktop.
Python 3.4 Urllib Basic Auth: the script sends JSON data via POST request using HTTP Basic authentication and urllib.
import urllib.request
import urllib.response
userName = "user"
passWord = "password"
top_level_url = "http://127.0.0.1/api/update"
# create an authorization handler
p = urllib.request.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, top_level_url, userName, passWord);
auth_handler = urllib.request.HTTPBasicAuthHandler(p)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
DATA = b'{"data": { "foo": "bar", "timestamp": 1466593290 }}'
try:
req = urllib.request.Request('http://127.0.0.1/api/update', data=DATA, headers={'Content-Type': 'application/json'})
result = opener.open(req)
messages = result.read()
print (messages)
except IOError as e:
print (e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment