Python requests post 提交form-data表单
问题:
对接接口,发现对方的接口使用form-data进行数据提交,直接使用requests库的data参数对接,会报参数错误:
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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
错误提示
解决方案
这一块Requests包做的不是很好,做法具体如下:
一种是手动组建form-data并加上headers;
另一种是通过files参数传递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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
结果