简体   繁体   中英

cURL GET request with body in Java

I have the following curl request:

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

which returns a JSON object.

How can I make such request and get the response in Java? I tried this:

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

But it returns an exception:

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

Based on the comments, managed to solve it myself.

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

}

That's not how sending data in Java works. The -d flag is for the CURL CLI only. In Java you should use a library like Apache HTTP Client: https://stackoverflow.com/a/3325065/5898512

Then parse the result with JSON: https://stackoverflow.com/a/5245881/5898512

As per your exception/error log, it clearly says that the service http://hostname:4444/grid/api/hub is receiving bad request(Status code 400).

And i think you need to check the service to which you are hitting and what exactly it accepts. Ex: the service may accept only application/json / application/x-www-form-urlencoded or the parameter to service that expecting but you are not sending that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM