Python - 如何发出REST POST请求

时间:2013-06-10 17:54:13

标签: java python rest post

我用Java实现了一个REST服务:

@POST
@Path("/policyinjection")
@Produces(MediaType.APPLICATION_JSON) 
public String policyInjection(String request) {

    String queryresult = null;
    String response = null;

    if (request == null) {
        logger.warning("empty request");
    } else {

        //call query() to query redisDB with the request
        queryresult = query(request);

        // call inject() to inject returned policy to floodlight
        response = inject(queryresult);

    }
    return response;
}

但我需要使用Python来实现客户端对上述服务发出POST请求。 我是python的新手,我想实现一个像这样的方法:

def callpolicyInjection():

3 个答案:

答案 0 :(得分:3)

我不确定这是您的完全问题的答案,但您应该查看requests模块。

它允许发送http POST请求(以及(m)任何其他http方法)主要在一行中发送:

>>> import requests

>>> keys = {'username':'Sylvain', 'key':'6846135168464431', 'cmd':'do_something'}
>>> r = requests.post("http://httpbin.org/post",params=keys)

现在,答案在r个对象:

>>> print(r)
<Response [200]>

>>> print(r.text)
{
  "origin": "70.57.167.19",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post?cmd=do_something&key=6846135168464431&username=Sylvain",
  "args": {
    "username": "Sylvain",
    "cmd": "do_something",
    "key": "6846135168464431"
  },
  "headers": {
    "Content-Length": "0",
    "Accept-Encoding": "identity, gzip, deflate, compress",
    "Connection": "close",
    "Accept": "*/*",
    "User-Agent": "python-requests/1.2.3 CPython/3.3.1 Linux/3.2.0-0.bpo.4-amd64",
    "Host": "httpbin.org"
  },
  "json": null,
  "data": ""
}

......这些只是例子。有关详细信息,请参阅请求response content文档。

答案 1 :(得分:1)

您可以使用requests lib。我不会这样做,因为它已经得到了解答。

您也可以使用urllib和urllib2:

import urllib
import urllib2

data = {
    'user': 'username',
    'pass': 'password'
}

urllib2.urlopen('http://www.example.com/policyinjection/', urllib.urlencode(data))

urllib2.urlopen的secode参数是与请求一起发送的数据。它是可选的,但如果您使用它,您的请求将自动成为POST。 urllib优于其他解决方案的优势在于它是标准发行版的一部分,因此您不会向应用程序添加任何额外的依赖项。

如果你想要表现,你应该使用pycurl

import pycurl

curl = pycurl.Curl()
curl.setopt(pycurl.URL, 'http://www.example.com/policyinjection/')
curl.setopt(pycurl.POSTFIELDS, 'user=username&pass=password')
curl.perform()

很遗憾,pycurl不属于标准版本,但您可以使用pip install pycurleasy_install pycurl进行安装。

答案 2 :(得分:0)

我已经专门为此目的制作了Nap,请查看它!

使用示例:

from nap.url import Url
api = Url('http://httpbin.org/')

response = api.post('post', data={'test': 'Test POST'})
print(response.json())

更多示例:https://github.com/kimmobrunfeldt/nap#examples