問題:
對接接口是复,發(fā)現(xiàn)對方的接口使用form-data進行數(shù)據(jù)提交给郊,直接使用requests庫的data參數(shù)對接,會報參數(shù)錯誤:
params = {
'timestamp':timestamp,
'nonce':nonce,
'apikey':APIKEY,
'signature': signature
}
data = {
'name': name,
'phone': phone,
'idnum': idnum,
'products': [201,]
}
resp = requests.post(URL, data=data, params=params,
verify=False, timeout=10)
錯誤提示
解決方案
這一塊Requests包做的不是很好勉痴,做法具體如下:
一種是手動組建form-data并加上headers我纪;
另一種是通過files參數(shù)傳遞form-datal;
# 方案一:
params = {
'timestamp':timestamp,
'nonce':nonce,
'apikey':APIKEY,
'signature': signature
}
payload = """------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;
name=\"phone\"\n\n{}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;
name=\"idnum\"\n\n{}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;
name=\"name\"\r\n\r\n{}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;
name=\"products\"\r\n\r\n {}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--""".format(phone, idnum, name, [201,])
headers = {
"content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
}
resp = requests.post(URL, data=payload, params=params,
verify=False, timeout=10, headers=headers)
# 方案二:
import json
params = {
'timestamp':timestamp,
'nonce':nonce,
'apikey':APIKEY,
'signature': signature
}
data = {
'name':(None, name),
'phone': (None, str(phone)),
'idnum': (None, idnum),
'products': (None, json.dumps([201,]))
}
resp = requests.post(URL, files=data, params=params,
verify=False, timeout=10)
print resp.status_code
print resp.request.url
print resp.request.body
print resp.text