一.問題描述
在使用post方法請求接口時,請求的內容中包含附件(這裏是圖片),
服務器需要用到圖片的名稱字段,來解析得到圖片的分類信息(例如,這張圖片屬於子單照片),
但是發送請求後,服務器報錯“必填參數爲空”,抓包分析發現上傳附件的文件名不正確,導致服務器無法正確解析文件名。
二.相關代碼
#coding=UTF-8
import requests
Base_URL = 'http://XX.XX.XX.XX'
def build_uri(endpoint):
return '/'.join([Base_URL, endpoint])
def post_method(url,data,files):
response = requests.post(url=url,data=data,files=files)
print(response.text)
if __name__ == '__main__':
file_name1 = 'value_1.txt'
with open(file_name1) as f1:
con = f1.read()
print(type(con))
print(con)
data = {"req": con}
headers = {"content-type": "multipart/form-data"}
files = {'864_子單照片_0': ("001_附件.jpg", open("001_附件.jpg", "rb"), "image/jpg", {})}
url = build_uri('mobile/postQCProblemCargo')
post_method(url, data, files)
三.解決方法
在網上嘗試了很多方法,大致就是post在發送數據時編碼和解碼問題
實測有效的方法:
修改requests庫所引用的urllib3庫的源文件fields.py
1.註釋掉圖中標記的一行(45行)
2.把圖中標記的一行(46行)修改爲:
value = '%s="%s"' % (name, value)
四.修改後請求抓包結果
可以看到,問題成功解決。