2010-03-03 61 views

回答

38

Python documentation

>>> import httplib, urllib 
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) 
>>> headers = {"Content-type": "application/x-www-form-urlencoded", 
...   "Accept": "text/plain"} 
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80") 
>>> conn.request("POST", "/cgi-bin/query", params, headers) 
>>> response = conn.getresponse() 
>>> print response.status, response.reason 
200 OK 
>>> data = response.read() 
>>> conn.close() 
+29

信貸到期的信用:直接從http://docs.python.org/release/2.6/library/httplib.html(或2.5.2或更早的版本,這些年來沒有太大改變) – dland 2012-02-06 14:40:19

+0

參數是否需要採用這種格式?他們可以是原始文本嗎? – 2013-02-13 14:55:36

+0

是的,你可以傳入原始文本作爲參數,'urllib.urlencode'只是照顧URL編碼的字符串傳遞,如果你打印出來,你會看到它只是一個字符串 – Ole 2013-04-29 09:15:27

10

一個更簡單的一個,僅使用的urllib:

import urllib 
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) 
f = urllib.urlopen("http://www.example.org/cgi-bin/query", params) 
print f.read() 

在Python文檔發現urllib module

+5

抱歉,但這最有可能做一個HTTP GET,而不是POST – hko 2013-10-29 15:26:33

+3

@hko不,它來自該urllib頁面上的POST示例。請注意,參數是用',params'而不是'%params'添加的。 – 2014-03-28 18:13:52

相關問題