簡體   English   中英

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 中構建一個代理,它必須使用計划器來解決游戲。 我使用的規划器在雲上作為服務運行,因此任何人都可以向它發送 HTTP 請求並獲得響應。 我必須向它發送一個JSON ,其內容如下: {"domain": "string containing the domain's description", "problem": "string containing the problem to be solved"} 作為回應,我得到一個JSON ,其中包含狀態和結果,這可能是一個計划或不是一個計划,這取決於是否存在問題。

以下代碼允許我調用規划器並接收其響應,從正文中檢索 JSON object:

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

這段代碼工作得很好,我沒有任何問題。 由於我必須對代理進行一些繁重的測試,我更喜歡在 localhost 上運行服務器,這樣服務就不會飽和(一次只能處理一個請求)。

但是,如果我嘗試向 localhost 上運行的服務器發送請求,則服務器收到的 HTTP 請求的主體為空。 不知何故,JSON 未發送,我收到包含錯誤的響應。

以下代碼說明了我如何嘗試向在 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();

為了測試,我之前創建了一個小的 Python 腳本,它將相同的請求發送到在 localhost 上運行的服務器:

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 點進行編碼/調試,這永遠不會正確)。 似乎問題在於我指定了我期望從服務器獲得的響應類型,而不是我試圖在請求正文中發送給它的響應:

HttpResponse 響應 = 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實例,其中包含將添加到請求正文中的信息。 通過這樣做,它可以在本地和雲服務器上運行。

盡管如此,我仍然不明白為什么當我調用雲服務器時我能夠得到正確的響應,但現在這並不重要。 我希望這個答案對面臨類似問題的人有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM