需求:模拟客户端进行post请求,除业务参数外,还需带有sign参数
在实现该需求时,使用了 requests.request()方法: requests.request('POST',url,data=rdata,cookies=rcookie),随后执行时遇到了以下问题:
1. <Response 403>
原因:缺失了header相关信息
解决方法:在header中添加 User-Agent 和 refer等相关信息
headers = {
'User-Agent': '...',
'referer': '....'
}
2. 提示 参数不合法
原因:请求的body中,需以 json 形式传参,而初始调用时使用的为data
解决方法:解决方法有俩,
① 因为request() 参数中本来即存在 json,可直接使用json来传参,即:
requests.request('POST',url,json=json.dumps(rdata),cookies=rcookie)
② 也可继续使用 data 参数,此时需指定 content-type:
headers = {'Content-Type': 'application/json'}
req = requests.request('POST',url,headers=headers,data=json.dumps(rdata),cookies=rcookie)
P.S. 若不指定content-type,data为dict时,默认为application/x-www-form-urlencoded;
data为str时,则默认为application/json。
网友评论