请求Python:传递有效负载PO​​ST请求

时间:2018-01-08 22:19:14

标签: python http request

我正在自动化网络设备的配置。我必须登录每个设备,更改网络地址和密码。 使用:Requests Python Module

我需要做的第一个过程是登录。这是一个简单的形式。通过检查网站,我将分析标题和必要的参数:

General:
Request URL:http://192.168.7.2:8000/api/login
Request Method:POST
Status Code:200 OK
Remote Address:192.168.7.2:8000
Referrer Policy:no-referrer-when-downgrade

Response Headers:
Transfer-Encoding:chunked

Request Headers:
POST /api/login HTTP/1.1
Host: 192.168.7.2:8000
Connection: keep-alive
Content-Length: 37
Accept: application/json, text/plain, */*
Origin: http://192.168.7.2:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://192.168.7.2:8000/login.html
Accept-Encoding: gzip, deflate
Accept-Language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7

Request Payload:
{"user":"user","password":"password"}

按照我在此代码中获得的文档:

import requests
import json

url = "http://192.168.7.2:8000/api/login"
payload = {"user":"admin","password":"admin"}
r = requests.post(url,data=payload)
#r.encoding = "UTF-8"
print r.text

会发生什么?好吧,运行脚本我收到此输出:{"errno":"20"}如果我使用用户/密码登录错误,则会出现同样的错误。这是不可能的,因为通过Web界面使用此用户/密码,验证成功。我认为代码中有问题。

更改有效负载格式:相同错误{"errno":"20"}

payload = (("user","admin"),("password","admin"))
r = requests.post(url,data=payload)
#r.encoding = "UTF-8"
print r.text

JSON-Enconded :报告其他错误:{"errno":"0","key":"fc2d253fb9b25d5880dd4843f439bc7b"}

import requests
import json

url = "http://192.168.7.2:8000/api/login"
payload = {"user":"admin","password":"admin"}
r = requests.post(url,data=json.dumps(payload))
#r.encoding = "UTF-8"
print r.text

直接传递json :报告{"errno":"0","key":"6f7ed0ae5f14833f689fcb34c2bf5b77"}

import requests
import json

url = "http://192.168.7.2:8000/api/login"
payload = {"user":"admin","password":"admin"}
r = requests.post(url,json=payload)
#r.encoding = "UTF-8"
print r.text

使用其他网址:

import requests
import json

url = "http://192.168.7.2:8000/login.html"
payload = {"user":"admin","password":"admin"}
r = requests.post(url,data=payload)
#r.encoding = "UTF-8"
print r.text

报告UnicodeEncodeError: 'ascii' codec can't encode characters in position 3426-3427: ordinal not in range(128)

打印r.encoding - > ISO-8859-1是输出。

设置r.encoding="utf-8"print r.text输出:UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 3426: ordinal not in range(128)

任何人都有使用此lib的经验吗?

1 个答案:

答案 0 :(得分:0)

您可能需要在标题中传递用户名和密码。

{{1}}