簡體   English   中英

Python相當於Curl HTTP的帖子

[英]Python equivalent of Curl HTTP post

我使用以下命令從命令行使用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的方法?

import urllib2

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

其中data是要POST的編碼數據。

您可以使用urllib對dict進行編碼,如下所示:

import urllib

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

使用請求模塊(標語: 人類的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