Send multiform post request of file using pycurl

123 views Asked by At

I am trying to hit Curl request with Python using pycurl.Need to send the file using post and file should be multiform data.

I can't use requests module due to some limitation, but Curl is throwing error Bad Requests.

import pycurl, json

url = "https://media.smsgupshup.com/GatewayAPI/rest"
c = pycurl.Curl()
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDSIZE, 0)
c.setopt(pycurl.URL, url)

c.setopt(pycurl.USERPWD, "AdminUserName:AdminPassword")
c.setopt(pycurl.HTTPHEADER, ['Content-Type : multipart/form-data',])
c.setopt(pycurl.VERBOSE, 1)

c.setopt(c.HTTPPOST, [
    ('fileupload', (
        # upload the contents of this file
        c.FORM_FILE, "C:\\Users\\Downloads\\Test.jpg",
        # specify a different file name for the upload
        c.FORM_FILENAME, 'Test.jpg',
        # specify a different content type
    )),
])


c.perform()

print('Status: %d' % c.getinfo(c.RESPONSE_CODE))
# Elapsed time for the transfer.
print('Time: %f' % c.getinfo(c.TOTAL_TIME))
c.close()

Error I am receiving in this is bad request: HTTP/1.0 400 Bad request

1

There are 1 answers

0
achrafhamid On

You'll need te delete the space between Content-Type and the colon in :

c.setopt(pycurl.HTTPHEADER, ['Content-Type : multipart/form-data',]) 

And the POSTFIELDSIZE shoud be set into the bytes size of the img you are sending. Otherwise you add in your HTTPPOST a FORM_BUFFER so that the POSTFIELDSIZE automatically considers the size of passed img.

...    
c.FORM_BUFFER, "Test.jpg",
...