我正在尝试使用 pycurl 通过 Python 发送 Curl 请求。需要使用 post 发送文件,文件应该是多格式数据。
由于某些限制,我无法使用请求模块,但 Curl 会抛出错误 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()
我收到的错误请求是错误的: HTTP/1.0 400 错误请求
你需要删除
Content-Type
和冒号之间的空格:
c.setopt(pycurl.HTTPHEADER, ['Content-Type : multipart/form-data',])
并且
POSTFIELDSIZE
应该设置为您发送的 img 的字节大小。否则,您在 HTTPPOST 中添加一个 FORM_BUFFER
,以便 POSTFIELDSIZE
自动考虑传递的 img 的大小。
...
c.FORM_BUFFER, "Test.jpg",
...