使用Python发出POST请求

时间:2013-06-21 06:35:41

标签: python

我正在尝试发出POST请求但是收到此错误:

Traceback (most recent call last):
  File "demo.py", line 7, in <module>
    r = requests.post(url, data=payload, headers=headers)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 87, in post
    return request('post', url, data=data, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 266, in request
    prep = req.prepare()
  File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 215, in prepare
    p.prepare_body(self.data, self.files)
  File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 338, in prepare_body
    body = self._encode_params(data)
  File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 74, in _encode_params
    for k, vs in to_key_val_list(data):
ValueError: too many values to unpack

这是我的计划:

import requests

url = 'http://www.n-gal.com/index.php?route=openstock/openstock/optionStatus'

payload = {'var:1945,product_id:1126'}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=payload, headers=headers)

我使用以下数据通过Advanced rest客户端尝试了相同的POST请求:

URL : http://www.n-gal.com/index.php?route=openstock/openstock/optionStatus payload : var=1945&product_id=1126 Content-Type: application/x-www-form-urlencoded

工作正常,任何人都可以帮助我...

4 个答案:

答案 0 :(得分:5)

您已将payload设为set,而不是字典。你忘了关闭字符串了。

变化:

payload = {'var:1945,product_id:1126'}

要:

payload = {'var':'1945','product_id':'1126'}

因为它是一个集合,所以请求将失败。

答案 1 :(得分:4)

试试这个:

import requests

url = 'http://www.n-gal.com/index.php?route=openstock/openstock/optionStatus'

payload = 'var=1945&product_id=1126'
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=payload, headers=headers)

print r.json()

答案 2 :(得分:0)

import requests
import json

url = 'http://www.n-gal.com/index.php?route=openstock/openstock/optionStatus'

payload = {'var:1945,product_id:1126'}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=json.dumps(payload), headers=headers)

答案 3 :(得分:0)

我知道这是一个非常老的问题,但是最近使用Docker时我遇到了同样的问题,并设法通过在需求中包含requests库来解决此问题(或仅使用{{1更新该库}}。

使用请求库的原始版本时,它在Python3.8上引发了同样的错误,该错误仅在升级后才停止。