Skip to content

Instantly share code, notes, and snippets.

@kaedea
Created September 12, 2019 06:18
Show Gist options
  • Save kaedea/d364aeaabc50b970020b0ae542e8cd15 to your computer and use it in GitHub Desktop.
Save kaedea/d364aeaabc50b970020b0ae542e8cd15 to your computer and use it in GitHub Desktop.
# 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