简体   繁体   English

django / python如何通过发布json连接到Web服务

[英]django/python How to connect to a webservice by posting a json

I am developing an application that connects to a web service, providing a json string with data and receiving a reply. 我正在开发一个连接到Web服务的应用程序,为它提供带有数据的json字符串并接收答复。 I use the following code, where I build the json and try to post it: 我使用以下代码,在其中构建json并尝试将其发布:

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. 我希望将来自Web服务的json回复存储在结果中,然后我想出一种可能的方法,可能是通过反序列化来解析它。 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. 尽管关于它的文献很多(json,simplejson,HttpPequest),而且它必须非常简单,但我还没有做到。 Any solutions? 有什么办法吗?

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 希望这会给你一个想法

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM