Python的Curl HTTP POST等效方法

21

我正在使用以下命令从命令行使用curl向Hudson服务器发送请求--

curl -X POST -d '<run><log encoding="hexBinary">4142430A</log><result>0</result><duration>2000</duration></run>' \
http://user:pass@myhost/hudson/job/_jobName_/postBuildResult

如Hudson文档所示,我能否使用Python来模拟相同的操作?我不想使用pyCurl或通过os.system()发送此行命令。是否有使用原始的Python的方法?


类似的问题在这里:https://dev59.com/dnI-5IYBdhLWcg3wKE-x - Jordan
2个回答

22
import urllib2

req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()

其中data是您要发送的编码数据。

您可以使用urllib将字典进行编码,如下所示:

import urllib

values = { 'foo': 'bar' }
data = urllib.urlencode(values)

简单明了,谢谢!不过,为了编码数据,我不得不使用 urllib.urlencode,因为找不到 encode - Scott Saad
我建议使用requests模块来进行HTTP请求(请参考Ashish Gulati的回答)。该库会自动处理url编码等问题,因此您可以将注意力集中在更重要的事情上。 - AllenMoh

21

现代化的解决方案变得更加简单,使用requests模块(标语: HTTP for humans! :)

import requests

r = requests.post('http://httpbin.org/post', data = {'key':'value'}, auth=('user', 'passwd'))
r.text      # response as a string
r.content   # response as a byte string
            #     gzip and deflate transfer-encodings automatically decoded 
r.json()    # return python object from json! this is what you probably want!

1
requests模块是真正的艺术品,也是完成工作的正确工具。这应该是被接受的答案。 - AllenMoh
1
这个回复对我的问题来说是最好的。谢谢。 - miguelmorales85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接