簡體   English   中英

Java中帶有正文的cURL GET請求

[英]cURL GET request with body in Java

我有以下卷曲請求:

curl -X GET http://hostname:4444/grid/api/hub -d '{"configuration":["slotCounts"]}'

它返回一個JSON對象。

我該如何發出這樣的請求並獲得Java的響應? 我嘗試了這個:

URL url = new URL("http://hostname:4444/grid/api/hub -d '{\"configuration\":[\"slotCounts\"]}'");

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(
            url.openStream(), "UTF-8"))) {
        for (String line; (line = reader.readLine()) != null;) {
            System.out.println(line);
        }
    }

但它返回一個異常:

Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: http://hostname:4444/grid/api/hub -d '{"configuration":["slotCounts"]}'

根據評論,自己解決了問題。

private static class HttpGetWithEntity extends
        HttpEntityEnclosingRequestBase {
    public final static String METHOD_NAME = "GET";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }
} 

private void getslotsCount() throws IOException,
        URISyntaxException {

    HttpGetWithEntity httpEntity = new HttpGetWithEntity();
    URL slots = new URL("http://hostname:4444/grid/api/hub");

    httpEntity.setURI(pendingRequests.toURI());

    httpEntity
            .setEntity(new StringEntity("{\"configuration\":[\""
                    + PENDING_REQUEST_COUNT + "\"]}",
                    ContentType.APPLICATION_JSON));
    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(getPendingRequests);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response
            .getEntity().getContent()));

    // At this point I can just get the response using readLine()
    System.out.println(rd.readLine());

}

這不是用Java發送數據的方式。 -d標志僅用於CURL CLI。 在Java中,您應該使用Apache HTTP Client之類的庫: https : //stackoverflow.com/a/3325065/5898512

然后使用JSON解析結果: https : //stackoverflow.com/a/5245881/5898512

根據您的異常/錯誤日志,它清楚地表明服務http://hostname:4444/grid/api/hub收到錯誤的請求(狀態代碼400)。

而且我認為您需要檢查您要使用的服務以及它所接受的服務。 例如:服務可能只接受application/json / application/x-www-form-urlencoded或要服務的參數,但您並未發送。

暫無
暫無

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

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