SimpleDao
Python http请求
2019-05-06, 访问数: 865

http请求

  1. def open_url(url, method='GET', headers=None, postform=None, postdata=None, timeout=10):
  2. """http请求"""
  3. try:
  4. if headers is None:
  5. headers = {}
  6. if postform is None:
  7. postform = {}
  8. if len(postform) > 0:
  9. data = urllib.urlencode(postform)
  10. headers['Content-Type'] = 'application/x-www-form-urlencoded'
  11. else:
  12. data = postdata
  13. req = urllib2.Request(url=url, data=data, headers=headers)
  14. req.get_method = lambda: method.upper()
  15. res = urllib2.urlopen(req, timeout=timeout)
  16. data = res.read()
  17. res.close()
  18. return res.code, res.headers, data
  19. except urllib2.HTTPError, e:
  20. data = e.read()
  21. e.close()
  22. return e.code, e.headers, data
  23. except Exception:
  24. log = traceback.format_exc().replace('\n', ' ')
  25. return 500, {}, log