使用urllib调用API传递文件时遭遇TypeError问题求助
问题解决方法
错误原因
- 请求头
headers的所有值必须是字符串或字节类型,你直接把文件对象放进请求头,这是触发TypeError: expected string or bytes-like object的核心原因。 urllib.request.urlopen的参数顺序错误:第三个参数是超时时间(整数/浮点数类型),不是请求头,你传入字典自然会出现'dict' object cannot be interpreted as an integer错误。
正确实现方式
文件上传需要采用multipart/form-data格式发送请求,urllib需要手动构造该格式的请求体,修正后的代码如下:
import urllib.request import uuid # 生成随机边界符,用于分隔表单字段 boundary = uuid.uuid4().hex content_type = f'multipart/form-data; boundary={boundary}' # 读取文件内容 with open('File.sql', 'rb') as f: file_content = f.read() # 构造符合multipart/form-data格式的请求体 body = ( f'--{boundary}\r\n' 'Content-Disposition: form-data; name="files[]"; filename="File.sql"\r\n' 'Content-Type: application/sql\r\n\r\n' ).encode('utf-8') + file_content + f'\r\n--{boundary}--\r\n'.encode('utf-8') # 初始化请求对象,传入正确的请求体和请求头 request = urllib.request.Request( 'https://www.rebasedata.com/api/v1/convert', data=body, headers={'Content-Type': content_type} ) try: response = urllib.request.urlopen(request) # 处理返回的响应内容 print(response.read().decode('utf-8')) except Exception as e: print(f'请求出错: {e}')
更简洁的替代方案(推荐)
如果可以使用requests库,无需手动构造请求体,代码会大幅简化:
import requests files = {'files[]': open('File.sql', 'rb')} response = requests.post('https://www.rebasedata.com/api/v1/convert', files=files) print(response.text)
内容的提问来源于stack exchange,提问作者Adrita Sharma
相关产品推荐
相关产品推荐

