歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python發送HTTP請求

Python發送HTTP請求

日期:2017/3/1 10:51:14   编辑:Linux編程

python發送HTTP請求 今天用python寫一個發送HTTP請求的功能,查了下文檔,發現實現也就4、5行左右,不禁感歎啊,查了下原來找的java實現的,相比還是臃腫了很多。 所以,python的好處還是蠻多的,對於 這些小的功能點相當適合。 附上官方的實例:

  1. 01 Here is an example session that uses the GET method:
  2. 02
  3. 03 >>> import httplib
  4. 04 >>> conn = httplib.HTTPConnection("www.python.org")
  5. 05 >>> conn.request("GET", "/index.html")
  6. 06 >>> r1 = conn.getresponse()
  7. 07 >>> print r1.status, r1.reason
  8. 08 200 OK
  9. 09 >>> data1 = r1.read()
  10. 10 >>> conn.request("GET", "/parrot.spam")
  11. 11 >>> r2 = conn.getresponse()
  12. 12 >>> print r2.status, r2.reason
  13. 13 404 Not Found
  14. 14 >>> data2 = r2.read()
  15. 15 >>> conn.close()
  16. 16
  17. 17 Here is an example session that uses the HEAD method. Note that the HEAD method never returns any data.
  18. 18
  19. 19 >>> import httplib
  20. 20 >>> conn = httplib.HTTPConnection("www.python.org")
  21. 21 >>> conn.request("HEAD","/index.html")
  22. 22 >>> res = conn.getresponse()
  23. 23 >>> print res.status, res.reason
  24. 24 200 OK
  25. 25 >>> data = res.read()
  26. 26 >>> print len(data)
  27. 27 0
  28. 28 >>> data == ''
  29. 29 True
  30. 30
  31. 31 Here is an example session that shows how to POST requests:
  32. 32
  33. 33 >>> import httplib, urllib
  34. 34 >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
  35. 35 >>> headers = {"Content-type": "application/x-www-form-urlencoded",
  36. 36 ... "Accept": "text/plain"}
  37. 37 >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
  38. 38 >>> conn.request("POST", "/cgi-bin/query", params, headers)
  39. 39 >>> response = conn.getresponse()
  40. 40 >>> print response.status, response.reason
  41. 41 200 OK
  42. 42 >>> data = response.read()
  43. 43 >>> conn.close()
Copyright © Linux教程網 All Rights Reserved