Python_requests 解决发送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)                   

错误提示

Python_requests 解决发送form-data格式请求_第1张图片
报错信息

解决方案

这一块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                     

结果

Python_requests 解决发送form-data格式请求_第2张图片
结果展示

你可能感兴趣的:(Python_requests 解决发送form-data格式请求)