Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Curl HTTP post

Tags:

python

http

curl

I am posting to Hudson server using curl from the command line using the following--

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??

like image 895
Arnab Sen Gupta Avatar asked Jul 14 '10 12:07

Arnab Sen Gupta


2 Answers

import urllib2

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

where data is the encoded data you want to POST.

You can encode a dict using urllib like this:

import urllib

values = { 'foo': 'bar' }
data = urllib.urlencode(values)
like image 112
Can Berk Güder Avatar answered Oct 11 '22 06:10

Can Berk Güder


The modern day solution to this is much simpler with the requests module (tagline: 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!
like image 43
Ashish Gulati Avatar answered Oct 11 '22 05:10

Ashish Gulati