Your code is mostly correct, but there is an error in OutputStream . As P .J said, an OutputStream is required to pass a request to the server to the body. If your rest service does not require any organ, you do not need to use this one.
To read the server, you need to use an InputStream (RJ will also show you an example):
try (InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) { byte[] buf = new byte[512]; int read = -1; while ((read = inputStream.read(buf)) > 0) { byteArrayOutputStream.write(buf, 0, read); } System.out.println(new String(byteArrayOutputStream.toByteArray())); }
This method is good if you do not want it to depend on the libraries of the third part. Therefore, I recommend you take a look at Jersey - a very nice library with lots of very useful features.
Client client = JerseyClientBuilder.newBuilder().build(); Response response = client.target("http://host:port"). path("test").path("db-api").path("processor").path("packages"). request().accept(MediaType.APPLICATION_JSON_TYPE).buildGet().invoke(); System.out.println(response.readEntity(String.class));
source share