Java Unirest 向本地主机上的服务器 运行 发送带有空 JSON 的 POST 请求,但在向云服务器发送相同请求时工作正常?

Java Unirest sends POST request with empty JSON to server running on localhost but works fine when sending the same request to cloud server?

我正在 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 对象:

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

这段代码工作得很好,我没有遇到任何问题。由于我必须对代理进行一些繁重的测试,我更喜欢 运行 本地主机上的服务器,这样服务就不会饱和(它一次只能处理一个请求)。

但是,如果我尝试向本地主机上的服务器 运行ning 发送请求,服务器收到的 HTTP 请求正文是空的。不知何故,JSON 没有发送,我收到了包含错误的响应。

以下代码说明了我如何尝试向本地主机上的服务器 运行ning 发送请求:

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

为了测试,我之前创建了一个小的 Python 脚本,它向本地主机上的服务器 运行ning 发送相同的请求:

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

执行脚本时,我得到了正确的响应,似乎 JSON 已正确发送到服务器。

有人知道为什么会这样吗?

好吧,幸运的是我找到了这个问题的答案(伙计们,不要在凌晨 2 点到 3 点尝试 code/debug,结果永远不会正确)。看来问题是我在请求的 body:

中指定了我期望从服务器获得什么样的响应,而不是我试图发送给它的响应

HttpResponse response = Unirest.post(url) .header("accept", "application/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();

现在我在 header 中指定我要发送的内容类型。此外,我还创建了一个 JSONObject 实例,其中包含将添加到请求的 body 中的信息。通过这样做,它可以在本地和云服务器上工作。

尽管如此,我仍然不明白为什么当我调用云服务器时能够得到正确的响应,但现在已经不重要了。我希望这个答案对面临类似问题的人有所帮助!