使用urllib2发出带标题的发布请求

时间:2014-07-22 08:18:04

标签: python http-post urllib2

我想向具有特定数据和标题类型的网址发送帖子请求。使用这两个链接,我发现如何做到这一点,但它不起作用:
https://stackoverflow.com/questions/5693931/python-post-request
How do I send a custom header with urllib2 in a HTTP Request?
这是我的代码:

import urllib
import urllib2

url = 'https://clients6.google.com/rpc'
values = [
    {"method": "pos.plusones.get",
     "id": "p",
     "params": {
                "nolog": True,
                "id": "http://www.newswhip.com",
                "source": "widget",
                "userId": "@viewer",
                "groupId": "@self"
                },
     "jsonrpc": "2.0",
     "key": "p",
     "apiVersion": "v1"
    }]
headers = {"Content-type" : "application/json:"}

data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page

我可以在Postman Rest Client中获得带有这些值的结果。但执行此代码后,结果为:

Traceback (most recent call last):
  File "D:/Developer Center/Republishan/republishan2/republishan2/test2.py", line 22, in <module>
    data = urllib.urlencode(values)
  File "C:\Python27\lib\urllib.py", line 1312, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object

我也尝试过使用字典而不是像这样的列表:

values = {"method": "pos.plusones.get",
     "id": "p",
     "params": {
                "nolog": True,
                "id": "http://www.newswhip.com",
                "source": "widget",
                "userId": "@viewer",
                "groupId": "@self"
                },
     "jsonrpc": "2.0",
     "key": "p",
     "apiVersion": "v1"
    }

它执行脚本但结果包含错误:

{"error":{"code":-32700,"message":"Unable to parse json","data":[{"domain":"global","reason":"parseError","message":"Unable to parse json"}]}}

正如我所说,我可以使用Postman Rest Client执行带有列表而不是字典的脚本。 看看Postman的结果: enter image description here 我该怎么办?

1 个答案:

答案 0 :(得分:3)

看起来urllib.urlencode并不了解嵌套的词组:

     In [38]: urllib.urlencode({"a": "asas", "df": {"sds": 123, "t": "fgfg"}})
     Out[38]: 'a=asas&df=%7B%27t%27%3A+%27fgfg%27%2C+%27sds%27%3A+123%7D'

或者你的例子:

     In [41]: urllib.urlencode(values)
     Out[41]: 'jsonrpc=2.0&apiVersion=v1&id=p&params=%7B%27nolog%27%3A+True%2C+%27source%27%3A+%27widget%27%2C+%27userId%27%3A+%27%40viewer%27%2C+%27id%27%3A+%27http%3A%2F%2Fwww.newswhip.com%27%2C+%27groupId%27%3A+%27%40self%27%7D&key=p&method=pos.plusones.get'

参见&#34; params&#34;搞砸了。

我不确定如何使用urllib解决这个问题。所以我推荐请求库。 http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers

简而言之,它看起来像这样(您需要先安装请求库,例如使用pip:pip install requests):

     import requests
     import json

     url = 'https://clients6.google.com/rpc'
     values = {
         "method": "pos.plusones.get",
         "id": "p",
         "params": {
                    "nolog": True,
                    "id": "http://www.newswhip.com",
                    "source": "widget",
                    "userId": "@viewer",
                    "groupId": "@self"
                   },
          "jsonrpc": "2.0",
          "key": "p",
          "apiVersion": "v1"
     }
     headers = {"content-type" : "application/json"}

     req = requests.post(url, data=json.dumps(values), headers=headers)
     print req.text

它对我有用。

相关问题