如何用Python编写带有请求的基本REST Post?

2024-03-29 11:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用Requests时遇到问题

我正在测试的API指示要在消息正文中发布的参数device_info。它还说设备信息是一个表单字段。在Requests的所有文档中,除了用json中的值填充名称之外,我找不到如何向参数添加“name”。这是我试过的。

import requests
import json

loginPayload = {'device_info':{'app-id':'fc','os-type':'ios'}}
loginHeaders = {'content-type': 'application/json','Authorization':'Basic base64here'}
loginUrl = "http://subdomain.test.com/endpoint/method"
loginPost = requests.post(loginUrl, params=json.dumps(loginPayload), headers=loginHeaders)

print loginPost.text

我试过把params=改成data=,但我没有运气。

我得到的回应是:

{
"response": {
"message": "Parameter 'device_info' has invalid value ()", 
"code": 400, 
"id": "8c4c51e4-9db6-4128-ad1c-31f870654374"
  }
}

编辑:

去个新地方!我没有修改代码如下:

import requests

login = 'test'
password = 'testtest'
url = "http://subdomain.domain.com/endpoint/method"

authentication = (login,password)
payload = {'device_info': {'device_id': 'id01'}}
request = requests.post(url, data=payload, auth=authentication)

print request.text

产生:

{
  "response": {
    "message": "Parameter 'device_info' has invalid value (device_id)", 
    "code": 400, 
    "id": "e2f3c679-5fca-4126-8584-0a0eb64f0db7"
  }
}

怎么回事?我没有按要求的格式提交吗?

编辑:解决方案正在将我的参数更改为:

{
    "device_info": "{\"app-id\":\"fc\",\"os-type\":\"ios\",\"device_id\":\"myDeviceID1\"}"
}

Tags: importinfoidjsonapp参数osdevice
1条回答
网友
1楼 · 发布于 2024-03-29 11:18:12

所以这里有几个问题:

  • 你没有说你发布的网站需要JSON数据,事实上在你的评论中你说“需要的编码是‘application/x-www-form-urlencoded’。”。
  • params引用查询字符串的参数。您需要的是data参数。

因此,如果您的应用程序正在查找“application/x-www-form-urlencoded”数据,则不应:

  • 设置Content-Type
  • 对有效载荷数据使用json.dumps

你应该做的是:

import requests

login_payload = {'device_info': {'app-id': 'fc', 'os-type': 'os'}}
authentication = (login, password)  # Anyone who sees your authorization will be able to get this anyway
url = 'http://example.com/login'
response = requests.post(url, data=login_payload, auth=authentication)

我不知道有一个RESTful API接受x-www-form-urlencoded数据,但您也可能不正确地描述了您的问题。你没有给我们太多的东西,也没有给我更多的猜测能力。因此,根据你所说的一切,这绝对是我最好的猜测。

相关问题 更多 >