简体   繁体   English

Python相当于Curl HTTP的帖子

[英]Python equivalent of Curl HTTP post

I am posting to Hudson server using curl from the command line using the following-- 我使用以下命令从命令行使用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

as shown in the hudson documentation..can I emulate the same thing using python..i don't want to use pyCurl or send this line through os.system()..is there ny way out using raw python?? 如hudson文档中所示..我可以使用python来模拟相同的事情。我不想使用pyCurl或通过os.system()发送此行..是否有使用原始python的方法?

import urllib2

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

where data is the encoded data you want to POST. 其中data是要POST的编码数据。

You can encode a dict using urllib like this: 您可以使用urllib对dict进行编码,如下所示:

import urllib

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

The modern day solution to this is much simpler with the requests module (tagline: HTTP for humans! :) 使用请求模块(标语: 人类的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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM