英文:
Send multiform post request of file using pycurl
问题
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
英文:
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
得分: 1
需要删除Content-Type
和冒号之间的空格:
c.setopt(pycurl.HTTPHEADER, ['Content-Type: multipart/form-data',])
并且POSTFIELDSIZE
应该设置为您发送的图像的字节大小。否则,您可以添加一个FORM_BUFFER
,使POSTFIELDSIZE
自动考虑传递的图像大小:
...
c.FORM_BUFFER, "Test.jpg",
...
英文:
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",
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论