Created
September 12, 2019 06:18
-
-
Save kaedea/d364aeaabc50b970020b0ae542e8cd15 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# HTTP REQUEST | |
def http_request(url, method=None, post_data=None, headers=None): | |
''' | |
Args: | |
url: HTTP URL | |
method: GET/POST/.. | |
post_data: <dict> | |
headers: <dict> | |
Returns: <dict> or None | |
''' | |
def check_format(name, value): | |
if value and not isinstance(value, dict): | |
raise Exception('{} should be dict!'.format(name)) | |
check_format('post_data', post_data) | |
check_format('headers', headers) | |
try: | |
if post_data: | |
request = urllib2.Request(url, json.dumps(post_data)) | |
else: | |
request = urllib2.Request(url) | |
if headers: | |
for key in headers: | |
request.add_header(key, headers[key]) | |
if method: | |
request.get_method = lambda: method | |
else: | |
method = request.get_method() | |
print('request http {}, url = {}, data = {}'.format(method.upper(), url, post_data)) | |
response = urllib2.urlopen(request) | |
content = response.read() | |
if content and (content.startswith('{') or content.startswith('[')): | |
return json.loads(content) | |
return content | |
except Exception as e: | |
print('request error, e = {}'.format(str(e))) | |
traceback.print_exc() | |
return None | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment