2

我已经用 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():
4

3 回答 3

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": ""
}

...这些只是例子。有关详细信息,请参阅请求响应内容文档。

于 2013-06-10T18:02:14.530 回答
1

You can use the requests lib. I won't cover this as it has already been answered.

You can also use urllib and urllib2:

import urllib
import urllib2

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

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

The secode parameter to urllib2.urlopen is the data to send along with the request. It is optional, but if you use it your request automatically becomes POST. The advantage of urllib over other solutions it that it's part of the standard distribution, so you won't add any extra dependencies to your application.

And if you want performance you should use 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()

Unfortunately, pycurl is not part of the standard distribution, but you can install it using pip install pycurl or easy_install pycurl.

于 2013-06-10T18:09:28.227 回答
0

我专门为此做了午睡,看看吧!

示例用法:

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

于 2013-12-16T20:17:47.913 回答