cURL用Java中的body请求

时间:2017-06-29 08:11:17

标签: java curl

我有以下卷曲请求:

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"]}'

3 个答案:

答案 0 :(得分:2)

根据评论,设法自己解决。

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

}

答案 1 :(得分:-1)

这不是Java中发送数据的方式。 -d标志仅用于CURL CLI。在Java中,您应该使用像Apache HTTP Client这样的库: https://stackoverflow.com/a/3325065/5898512

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

答案 2 :(得分:-1)

根据您的异常/错误日志,它清楚地表明服务http://hostname:4444/grid/api/hub正在接收错误请求(状态代码400)。

我认为您需要检查您正在接受的服务以及它接受的内容。例如:该服务可能只接受application/json / application/x-www-form-urlencoded或服务期望但不发送的参数。