简体   繁体   English

复制curl命令python 3 urllib请求API

[英]replicate curl command python 3 urllib request API

This problem is kind of driving me crazy. 这个问题有点使我发疯。 I'm doing a very simple python 3 script to manage an API in a public website. 我正在做一个非常简单的python 3脚本来管理公共网站中的API。 I am able to do it with curl, but not in pyhton. 我可以卷发,但无法在pyhton中使用。 Can't use either requests library or curl in my real environment, just for tests 不能在我的真实环境中使用请求库或curl,仅用于测试

This is working: 这正在工作:

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

and we can see this in the curl debug: 我们可以在curl调试中看到这一点:

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

0000: POST /api-path HTTP/1.1 0000:POST / api-path HTTP / 1.1

0034: Host: XXXXXXXXXXXXXXXX 0034:主持人:XXXXXXXXXXXXXXXX

0056: User-Agent: curl/7.47.0 0056:用户代理:curl / 7.47.0

006f: Accept: / 006f:接受: /

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

00e3: Content-Length: 60 00e3:内容长度:60

00f7: Content-Type: application/x-www-form-urlencoded 00f7:内容类型:应用程序/ x-www-form-urlencoded

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

0000: json={"devices" : ["00:1A:1E:29:73:B2","00:1A:1E:29:73:B2"]} == Info: upload completely sent off: 60 out of 60 bytes 0000:json = {“ devices”:[“ 00:1A:1E:29:73:B2”,“ 00:1A:1E:29:73:B2”]} ==信息:完全发送:60 60字节

This is the python code to replicate the second request, which is the problematic one 这是复制第二个请求的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')

And the server is completely ignoring the Json content. 服务器完全忽略了Json内容。 Everything else is working, login and other url parameters from the same API 其他所有工作,登录和来自同一API的其他url参数

Any ideas? 有任何想法吗?

Try this: 尝试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM