如何通过使用python通过Rest API将POST请求作为JSON发送?

时间:2016-06-14 08:18:23

标签: python json rest http post

我通过使用来自platfora的python通过Rest API获得响应体。代码如下:

p = urllib.request.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, top_level_url, userName, passWord);
auth_handler = urllib.request.HTTPBasicAuthHandler(p)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
result = opener.open(top_level_url)

然后我用以下代码更改结果

result = opener.open(top_level_url)
messages = result.read().decode('utf-8')
dictinfo = simplejson.loads(messages)

#The dictinfo is a dictionary type and I find the dataset body which I need. The dataset is named as "changeName” and it is a dictionary as following.

data = {
    'ids': [12, 3, 4, 5, 6 , ...]
}

#Finally, I try to post "changeName" to platfora.
#The code is as following:

auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password('platfora_api', top_level_url, userName,   passWord);
opener = urllib.request.build_opener(auth_handler)

req = urllib.request.Request(top_level_url)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = simplejson.dumps(body)
jsondataasbytes = jsondata.encode('utf-8')  # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
urllib.request.install_opener(opener)
urllib.request.urlopen(req, jsondataasbytes)

#I meet the Error: urllib.error.HTTPError: HTTP Error 412: Precondition Failed

0 个答案:

没有答案