1

I have get response body through Rest API by using python from platfora. The code is following:

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)

Then I change the result with following codes

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
user94559
  • 59,196
  • 6
  • 103
  • 103
matcha latte
  • 185
  • 1
  • 12
  • Take a look at my answer to [this thread](https://stackoverflow.com/questions/34417279/sending-a-json-string-as-a-post-request/34418733#34418733) – rocksteady Jun 14 '16 at 08:28
  • It's not an answer but I might look at the ``requests`` package to simplify much of that. I believe it is recommended by even the python core maintainers. – nephlm Jun 14 '16 at 08:30

0 Answers0