Python相当于Curl HTTP的帖子

Arn*_*pta 17 python curl http

我使用以下命令从命令行使用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
Run Code Online (Sandbox Code Playgroud)

如hudson文档中所示..我可以使用python来模拟相同的东西.我不想使用pyCurl或通过os.system()发送此行..是否有使用原始python的方法?

Can*_*der 21

import urllib2

req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
Run Code Online (Sandbox Code Playgroud)

其中data是要POST的编码数据.

您可以使用urllib对dict进行编码,如下所示:

import urllib

values = { 'foo': 'bar' }
data = urllib.urlencode(values)
Run Code Online (Sandbox Code Playgroud)


小智 8

使用requests模块,现代的解决方案要简单得多(标语:人类的HTTP!:)

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!
Run Code Online (Sandbox Code Playgroud)