我正在用Java构建一个必须使用计划程序解决游戏的代理。 The planner that I am using作为服务在云上运行,因此任何人都可以向其发送HTTP请求并获得响应。我必须将以下内容发送给它:JSON
。作为响应,我得到一个{"domain": "string containing the domain's description", "problem": "string containing the problem to be solved"}
,其中包含状态和结果,这可能是一个计划,取决于是否存在问题。
下面的代码使我可以调用计划程序并接收其响应,并从主体中检索JSON对象:
JSON
此代码完全可以正常工作,我对此没有任何问题。由于必须在代理上进行大量测试,因此我更喜欢在localhost上运行服务器,以使服务不会饱和(一次只能处理一个请求)。
但是,如果我尝试向本地主机上运行的服务器发送请求,则该服务器收到的HTTP请求的正文为空。不知何故,未发送JSON,并且我收到包含错误的响应。
以下代码说明了我如何尝试向本地主机上运行的服务器发送请求:
String domain = readFile(this.gameInformation.domainFile);
String problem = readFile("planning/problem.pddl");
// Call online planner and get its response
String url = "http://solver.planning.domains/solve";
HttpResponse<JsonNode> response = Unirest.post(url)
.header("accept", "application/json")
.field("domain", domain)
.field("problem", problem)
.asJson();
// Get the JSON from the body of the HTTP response
JSONObject responseBody = response.getBody().getObject();
为了测试,我以前创建了一个小的Python脚本,该脚本将相同的请求发送到在localhost上运行的服务器:
// Call online planner and get its response
String url = "http://localhost:5000/solve";
HttpResponse<JsonNode> response = Unirest.post(url)
.header("accept", "application/json")
.field("domain", domain)
.field("problem", problem)
.asJson();
执行脚本时,我得到正确的响应,并且似乎JSON已正确发送到服务器。
有人知道为什么会这样吗?
[好,幸运的是,我已经找到了解决这个问题的方法(不要试图在2-3AM的人之间进行编码/调试,这永远都不会对的)。似乎问题是我正在指定我希望从服务器获得什么样的响应,而不是我试图在请求的正文中发送给它的响应:
HttpResponse响应= Unirest.post(url).header(“ accept”,“ application / json”)...
我能够通过以下操作解决我的问题:
import requests
with open("domains/boulderdash-domain.pddl") as f:
domain = f.read()
with open("planning/problem.pddl") as f:
problem = f.read()
data = {"domain": domain, "problem": problem}
resp = requests.post("http://127.0.0.1:5000/solve", json=data)
print(resp)
print(resp.json())
现在,我在标题中指定要发送的内容类型。另外,我创建了一个// Create JSON object which will be sent in the request's body
JSONObject object = new JSONObject();
object.put("domain", domain);
object.put("problem", problem);
String url = "http://localhost:5000/solve";
<JsonNode> response = Unirest.post(url)
.header("Content-Type", "application/json")
.body(object)
.asJson();
实例,其中包含将添加到请求正文中的信息。这样,它就可以在本地服务器和云服务器上使用。
尽管如此,我仍然无法真正理解为什么当我呼叫云服务器时我能够获得正确的响应,但是现在已经不重要了。我希望这个答案对面临此类问题的人有所帮助!