2

I am developing an application that connects to a web service, providing a json string with data and receiving a reply. I use the following code, where I build the json and try to post it:

def connectToService(request):
    data='foxp3 factor'
    l=[] 
    l.append(data)
    l.append(80)
    l.append(5)
    data=json.dumps({"findCitations":l})
    result = urllib2.urlopen('http://www.example.com/webservice', urllib.urlencode(data))

But it doesn't work. I hope that the json reply from the web service will be stored in result and then I will figure out a way to parse it, probably by deseriazizing it. Although there is much literature about it (json, simplejson, HttpPequest) and it has to be pretty simple I have not manage to do it yet. Any solutions?

2 Answers 2

3

Why not you are using the requests library

Like

payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://www.example.com/webservice", data=payload)
>>> print r.text

Where payload is the parameter that you are passing .

Hope this will give you an idea

Sign up to request clarification or add additional context in comments.

3 Comments

I think it is very enlightening. Thank you very much. I will try it!
@Jon Clements,I tried that but I have not achieved my target yet. I tried this in shell. After performing the request in 'print r.text' it returns a link and no data, which is exactly the same link I see when I put the url in the browser. From this I assume that the service didn't send any data back? I also use headers={"Content-type":"application/json", "encoding":"utf-8"} in the r=requests.post(url, data=json.dumps(payload), headers=headers). Any comment on this? I also try to find another api available to the web to test my code. Do you have something in mind?
Ok I did it. I called the service again, but this time with the url that returned in the first call and it worked. Thanks a lot for the advise.
1

You can use this code and some error handling idea:

    payload = {'key1': 'value1', 'key2': 'value2'}
    url = "http://www.example.com/webservice"

    try:
        response = requests.post(url, data=payload)

    except requests.exceptions.ConnectionError:
        message = 'This is not the domain we are looking for. URL is: %s' % url
        print e
        sys.exit(1)

    except requests.exceptions.ConnectTimeout:
        message = 'Too slow connection! URL is: %s' % url
        print e
        sys.exit(1)

    except Exception as e:
        message = 'Unknown Error: %(message)s URL is: %(url)s' % {'message': str(e), 'url': url}
        print e
        sys.exit(1)

    else:
        return response.json()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.