java - Java 中带有主体的 cURL GET 请求

标签 java curl

我有以下 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"]}'

最佳答案

根据评论,我自己解决了。

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 - Java 中带有主体的 cURL GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44819628/

相关文章:

java - 更改和删除按钮的方法

php - 来自 cURL : #3: <url> malformed 的错误

java - 如何将 Tomcat 重写阀添加到 Spring Boot 2.0 应用程序

Java - 设置上下文属性(ServletContextListener)

java - 在 JTable 中显示图像

java - 在eclipse IDE中手动添加包依赖

linux - Bash Linux Curl 从变量发送 header

ubuntu - 无法通过curl使用nova,需要身份验证

laravel - 运行 curl 命令以创建新的 Laravel 项目时,Docker 未运行

c# - C# 中的 cURL 模拟?