我有以下 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/