复制curl命令python 3 urllib请求API

时间:2017-07-25 14:24:44

标签: python-3.x curl httprequest

这个问题让我发疯了。 我正在做一个非常简单的python 3脚本来管理公共网站中的API。 我可以用curl来做,但不能用pyhton做。 在我的真实环境中不能使用请求库或curl,仅用于测试

这是有效的:

curl -d "credential_0=XXXX&credential_1=XXXXXX" -c cookiefile.txt https://XXXXXXXXXXXXXXX/LOGIN

curl -d 'json={"devices" : ["00:1A:1E:29:73:B2","00:1A:1E:29:73:B2"]}' -b cookiefile.txt -v https://XXXXXXXXX/api-path --trace-ascii /dev/stdout

我们可以在curl debug中看到这个:

发送标头,298字节(0x12a)

0000:POST / api-path HTTP / 1.1

0034:主持人:XXXXXXXXXXXXXXXX

0056:User-Agent:curl / 7.47.0

006f:接受: /

007c:Cookie:csrf_token = 751b6bd9-0290-496b-820e-XXXXXXXX;会议 00bc:= XXXXXX-6d29-4cf9-8907-XXXXXXXXXXXX

00e3:内容长度:60

00f7:内容类型:application / x-www-form-urlencoded

0128: =>发送数据,60字节(0x3c)

<00> 0000:json = {&#34; devices&#34; :[&#34; 00:1A:1E:29:73:B2&#34;,&#34; 00:1A:1E:29:73:B2&#34;]} ==信息:上传已完全发送:60个字节中的60个

这是复制第二个请求的python代码,这是有问题的一个

string_query={"devices" : [ "34:FC:B9:CE:14:7E","00:1A:1E:29:73:B2" ]}
jsonbody_url=urllib.parse.urlencode(string_query)
jsonbody_url=jsonbody_url.encode("utf-8")

req=urllib.request.Request(url,data=jsonbody_url,headers={"Cookie" : 
cookie,"Content-Type": "application/x-www-form-urlencoded","User-
Agent":"curl/7.47.0","charset":"UTF-8","Content-
length":len(jsonbody_url),
"Connection": "Keep-Alive"},method='POST')

服务器完全忽略了Json内容。 其他所有工作,登录和来自同一API的其他网址参数

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

import requests

string_query={"devices" : [ "34:FC:B9:CE:14:7E","00:1A:1E:29:73:B2" ]}
headers={
  "Cookie" : cookie,
  "Content-Type": "application/x-www-form-urlencoded",
  "User-Agent":"curl/7.47.0",
  "charset":"UTF-8",
  "Connection": "Keep-Alive"
}
response = requests.post(url,data=string_query,headers=headers)
print(response.content)