调用第三方接口(java),发送文件,一直说接收不到文件
1. 初始发送方式
url=""
data = {}
files = {"file": "文件流"}
headers = {"content-type": "multipart/form-data"}
response = requests.post(url=url, json=data, files=files, headers=headers, verify=False)
2. 解决问题后发送方式,使用MultipartEncoder
import requests
from requests.packages.urllib3.fields import RequestField
from requests.packages.urllib3.filepost import encode_multipart_formdata
def send_file_with_requests(url, file_path):
# 打开文件并读取内容
with open(file_path, 'rb') as file:
file_data = file.read()
# 创建请求字段列表
fields = [
('file', ('filename.txt', file_data, 'text/plain')),
]
# 创建请求字段列表,包含文件和其他参数(如果有)
fields = [RequestField.from_tuples(f) for f in fields]
# 创建 MultipartEncoder 对象
encoder = encode_multipart_formdata(fields)
# 创建请求对象并发送请求
response = requests.post(url, data=encoder, headers={'Content-Type': encoder.content_type})
# 处理响应
if response.status_code == 200:
print('文件发送成功')
print(response.text)
else:
print('文件发送失败')
print('HTTP Status Code:', response.status_code)
print('Response:', response.text)
# 使用示例
file_path = 'path/to/your/file.txt' # 替换为实际的文件路径
url = 'http://example.com/upload' # 替换为实际的上传文件接口的URL
send_file_with_requests(url, file_path)