Created
September 22, 2016 17:34
-
-
Save artttj/35ef14ed6b1b65a075c85bd5d6210f4f 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
helpful!