繁体   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