Python发送HTTP请求


python发送HTTP请求 今天用python写一个发送HTTP请求的功能,查了下文档,发现实现也就4、5行左右,不禁感叹啊,查了下原来找的java实现的,相比还是臃肿了很多。 所以,python的好处还是蛮多的,对于 这些小的功能点相当适合。 附上官方的实例:

  1. 01 Here is an example session that uses the GET method:    
  2.   
  3. 02      
  4.   
  5. 03 >>> import httplib    
  6.   
  7. 04 >>> conn = httplib.HTTPConnection("www.python.org")    
  8.   
  9. 05 >>> conn.request("GET""/index.html")    
  10.   
  11. 06 >>> r1 = conn.getresponse()    
  12.   
  13. 07 >>> print r1.status, r1.reason    
  14.   
  15. 08 200 OK    
  16.   
  17. 09 >>> data1 = r1.read()    
  18.   
  19. 10 >>> conn.request("GET""/parrot.spam")    
  20.   
  21. 11 >>> r2 = conn.getresponse()    
  22.   
  23. 12 >>> print r2.status, r2.reason    
  24.   
  25. 13 404 Not Found    
  26.   
  27. 14 >>> data2 = r2.read()    
  28.   
  29. 15 >>> conn.close()    
  30.   
  31. 16      
  32.   
  33. 17 Here is an example session that uses the HEAD method. Note that the HEAD method never returns any data.    
  34.   
  35. 18      
  36.   
  37. 19 >>> import httplib    
  38.   
  39. 20 >>> conn = httplib.HTTPConnection("www.python.org")    
  40.   
  41. 21 >>> conn.request("HEAD","/index.html")    
  42.   
  43. 22 >>> res = conn.getresponse()    
  44.   
  45. 23 >>> print res.status, res.reason    
  46.   
  47. 24 200 OK    
  48.   
  49. 25 >>> data = res.read()    
  50.   
  51. 26 >>> print len(data)    
  52.   
  53. 27 0   
  54.   
  55. 28 >>> data == ''    
  56.   
  57. 29 True   
  58.   
  59. 30      
  60.   
  61. 31 Here is an example session that shows how to POST requests:    
  62.   
  63. 32      
  64.   
  65. 33 >>> import httplib, urllib    
  66.   
  67. 34 >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})    
  68.   
  69. 35 >>> headers = {"Content-type""application/x-www-form-urlencoded",    
  70.   
  71. 36 ...            "Accept""text/plain"}    
  72.   
  73. 37 >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")    
  74.   
  75. 38 >>> conn.request("POST""/cgi-bin/query"params, headers)    
  76.   
  77. 39 >>> response = conn.getresponse()    
  78.   
  79. 40 >>> print response.status, response.reason    
  80.   
  81. 41 200 OK    
  82.   
  83. 42 >>> data = response.read()    
  84.   
  85. 43 >>> conn.close()   

相关内容