2

I want to get POST Web service data in python. For that purpose, I tried below:

import requests
import json

headers = {'content-type': 'application/json','charset': 'utf-8'}
url = 'https://a.b.c.com/count/WebService.asmx/ReadJSON'
data = {'tick': '123456A123456B'}
response = requests.post(url, data=json.dumps(data), headers=headers)
print response.status_code
print response.text

Above code output:

200
{"a":""}

But Actually, key "a" has some value which I'm not getting. I don't understand it's giving me status code as 200 i.e. OK then why I'm not able to get the proper JSON response. Is I missed something in code?

2
  • use response.json() instead of response.text and you don't need to dump your dictionary to string, you can pass it as is Commented Oct 9, 2017 at 6:45
  • If I passed, response = requests.post(url, data=data, headers=headers) I'm getting {u'StackTrace': u'', u'Message': u'There was an error processing the request.', u'ExceptionType': u''} error. Commented Oct 9, 2017 at 6:49

1 Answer 1

4

You should use json=data to pass json in requests but not manually modify headers, and you should use response.json() to get json result if you make sure it is.

import requests

headers = {'charset': 'utf-8'}
url = 'https://a.b.c.com/count/WebService.asmx/ReadJSON'
data = {'tick': '123456A123456B'}
response = requests.post(url, json=data, headers=headers)
print response.status_code
print response.json()
Sign up to request clarification or add additional context in comments.

7 Comments

@Sraw- Please see above comment. I tried your solution it's not working for me. I'm getting same output as shown in answer.
@kit Are you sure you are using json=data but not data=data?
@Sraw- Yes. I'm using json=data only. I changed it from data=data to json=data.
@kit you could print out response.request.headers to compare two different implementations. Further, if it really doesn't work for you because of some strange reasons, you can just change to use response.json() to get json result.
@Sraw- I'm getting response.request.header as {'Content-Length': '47', 'Accept-Encoding': 'gzip, deflate', 'Accept': '/', 'User-Agent': 'python-requests/2.18.4', 'Connection': 'keep-alive', 'Content-Type': 'application/json'} and I used respose.json() only to see the data.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.