如何在python中执行json请求

时间:2012-12-13 13:30:17

标签: python python-2.7

我想为Pocket开发一个python客户端(以前会读它)。

我正在研究it的OAuth流程。并被困在这里。如何执行此请求并获得响应?

POST /v3/oauth/request HTTP/1.1
Host: getpocket.com
Content-Type: application/json; charset=UTF-8
X-Accept: application/json

{"consumer_key":"1234-abcd1234abcd1234abcd1234",
"redirect_uri":"pocketapp1234:authorizationFinished"}

我是python的新手。这是我试过的。但我无法得到我想要的回应。

#!/usr/bin/env python

import urllib2
import json

def main():
    # Whatever structure you need to send goes here:
    jdata = json.dumps({"consumer_key":"1234-abcd1234abcd1234abcd1234", "redirect_uri":"pocketapp1234:authorizationFinished"})
    response = urllib2.urlopen("http://getpocket.com", jdata)
    the_page = response.read()
    print the_page

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:3)

使用requests库进行此类工作。 (修改)

import requests
import json


data = {"consumer_key": "..."}
headers = {"content-type": "application/json"}
response = requests.post("http://getpocket.com", data=json.dumps(data), headers=headers)
response.json