如何在python 2.4 中通过urllib2 提交post 数据?
How to submit post data via urllib2 in python 2.4?
我正在尝试使用 json 格式提交 POST 请求以使用 Crowd API.
创建用户
这是代码片段:
url = 'http://crowdserver/crowd/rest/usermanagement/1/user'
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample@user.cool"}'
req = urllib2.Request(url, payload)
req.add_header('Content-type','application/json')
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
output = resp.read()
print output
print resp.code
我得到以下输出:
Bad Request
Error code returned is 400
我认为这可能是编码问题,因此将有效负载替换为:
payload = json.dumps({"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample@user.cool"})
哪个returns:
NameError: name 'true' is not defined
看来 "active": true
的格式不可接受。
如果我添加双引号,例如 "active":"true"
,我会得到一个 TypeError; TypeError: not a valid non-string sequence or mapping object
更新
所以通过将 active
属性值设置为 True
确实解决了类型错误,但由于 invalid user data, for example missing password or the user already exists
读取为 400
结果返回了 400
错误the user already exists
- 我觉得奇怪的是,无效输入错误和现有用户共享相同的错误代码。
这一行:
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample@user.cool"}'
将..., "active": true, ...
更改为..., "active": True, ...
Python的True
/False
区分大小写。
我正在尝试使用 json 格式提交 POST 请求以使用 Crowd API.
创建用户这是代码片段:
url = 'http://crowdserver/crowd/rest/usermanagement/1/user'
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample@user.cool"}'
req = urllib2.Request(url, payload)
req.add_header('Content-type','application/json')
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
output = resp.read()
print output
print resp.code
我得到以下输出:
Bad Request
Error code returned is 400
我认为这可能是编码问题,因此将有效负载替换为:
payload = json.dumps({"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample@user.cool"})
哪个returns:
NameError: name 'true' is not defined
看来 "active": true
的格式不可接受。
如果我添加双引号,例如 "active":"true"
,我会得到一个 TypeError; TypeError: not a valid non-string sequence or mapping object
更新
所以通过将 active
属性值设置为 True
确实解决了类型错误,但由于 invalid user data, for example missing password or the user already exists
读取为 400
结果返回了 400
错误the user already exists
- 我觉得奇怪的是,无效输入错误和现有用户共享相同的错误代码。
这一行:
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample@user.cool"}'
将..., "active": true, ...
更改为..., "active": True, ...
Python的True
/False
区分大小写。