python用https post上传字符串[重复]

Posted

技术标签:

【中文标题】python用https post上传字符串[重复]【英文标题】:python upload string with https post [duplicate] 【发布时间】:2018-10-04 18:58:14 【问题描述】:

我们想用 python 上传一个字符串。 我找到了here 一些示例并创建了以下脚本。

import requests
url = 'https://URL/fileupload?FileName=file.csv'
headers = 'content-type': 'octet-stream'
files = 'file': ('ID,Name\n1,test')
r = requests.post(url, files=files, headers=headers, auth=('user', 'password'))

上传正常,但输出包含一些意外的行。

--ec7b507f800f48ab85b7b36ef40cfc44
Content-Disposition: form-data; name="file"; filename="file"

ID,Name
1,test
--ec7b507f800f48ab85b7b36ef40cfc44--

目标是仅从files = 'file': ('ID,Name\n1,test') 上传以下内容:

ID,Name
1,test

这怎么可能?

【问题讨论】:

【参考方案1】:

使用files 参数时,requests 创建发布文件所需的标题和正文。 如果您不希望您的请求格式如此,您可以使用data 参数。

url = 'http://httpbin.org/anything'
headers = 'content-type': 'application/octet-stream'
files = 'file': 'ID,Name\n1,test'
r = requests.post(url, data=files, headers=headers, auth=('user', 'password'))
print(r.request.body)
file=ID%2CName%0A1%2Ctest

请注意,当将字典传递给 data 时,它会进行 url 编码。如果您想提交不带任何编码的数据,您可以使用字符串。

url = 'http://httpbin.org/anything'
headers = 'content-type': 'application/octet-stream'
files = 'ID,Name\n1,test'
r = requests.post(url, data=files, headers=headers, auth=('user', 'password'))
print(r.request.body)
ID,Name
1,test

【讨论】:

以上是关于python用https post上传字符串[重复]的主要内容,如果未能解决你的问题,请参考以下文章

通过 $_POST 将文件上传到服务器 [重复]

python post提交数据

用python复制form表单的一个问题?

c用libcurl库实现https下get/post网络通信

Excel催化剂开源第34波-SM.MS图床API调用(用POST上传multipart/form-data内容)

https请求的post接口对数据的大小有限制吗