Created
March 10, 2013 21:55
-
-
Save whitews/5130653 to your computer and use it in GitHub Desktop.
Example script to send an HTTPS POST via httplib
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 sys | |
import httplib | |
from httplib import HTTPException | |
import json | |
DEBUG = False | |
BOUNDARY = '--------Boundary' | |
def post_stuff(host, post_url, field_dict): | |
""" | |
POST to a url | |
field_dict: a dictionary with field name as the key, and field's value as the value | |
Returns a dictionary with keys: | |
'status': The HTTP response code | |
'reason': The HTTP response reason | |
'headers': The HTTP response headers | |
'data': The HTTP response data | |
""" | |
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY | |
body = list() | |
for field in field_dict: | |
# add a field and value to body | |
body.append('--%s' % BOUNDARY) | |
body.append('Content-Disposition: form-data; name="%s"' % field) | |
body.append('') | |
body.append(field_dict['field']) | |
body.append('--' + BOUNDARY + '--') | |
body.append('') | |
body = '\r\n'.join(body) | |
conn = httplib.HTTPSConnection(host) | |
if DEBUG: | |
conn.set_debuglevel(1) | |
headers = { | |
'User-Agent': 'python', | |
'Content-Type': content_type, | |
'Content-Length': str(len(body)), | |
'Connection': 'keep-alive', | |
} | |
conn.request('POST', post_url, body, headers) | |
try: | |
response = conn.getresponse() | |
except Exception, e: | |
print e.__class__ | |
return { | |
'status': None, | |
'reason': 'No response', | |
'data': '', | |
'headers': '' | |
} | |
if response.status in [200, 201]: | |
try: | |
resp = response.read() | |
headers = response.getheaders() | |
except HTTPException, e: | |
print e | |
return { | |
'status': response.status, | |
'reason': 'Could not read response', | |
'data': '', | |
'headers': '' | |
} | |
try: | |
data = json.loads(resp) | |
except Exception, e: | |
data = resp | |
print e | |
else: | |
data = response.read() | |
return { | |
'status': response.status, | |
'reason': response.reason, | |
'headers': headers, | |
'data': data, | |
} | |
# Example code to run, make sure to change the host, post_url, and field_dict values | |
host = "localhost:443" # change me | |
post_url = '/some/url/' | |
field_dict = {'some_field':42, 'another_field':23} | |
response_dict = post_stuff(host, post_url, field_dict) | |
print "Response: ", response_dict['status'], response_dict['reason'] | |
print "Headers: " | |
print response_dict['headers'] | |
print "Data:" | |
print response_dict['data'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment