Forked from artttj/Python_Urllib_Basic_Auth_Query.py
Created
February 16, 2019 19:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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