gpt4 book ai didi

java - Python - 如何发出 REST POST 请求

转载 作者:行者123 更新时间:2023-11-28 22:55:20 24 4
gpt4 key购买 nike

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

最佳答案

我不确定这是否是您确切问题的答案,但您应该查看 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有关详细信息的文档。

关于java - Python - 如何发出 REST POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17029940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com