Make An Asynchronous GET in HTTP 2 Client in Java 9


Configured to run the program in Eclipse IDE: Select the java file containing the main function. Right click and select Run As/Run Configuration. Select Arguments and copy code: –add-modules jdk.incubator.httpclient to VM arguments Textbox

package pmk.learnjava9withrealapps.http2_client;

import java.net.URI;
import java.util.concurrent.CompletableFuture;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;

public class Main {

	public static void main(String[] args) {

		try {
			HttpClient httpClient = HttpClient.newHttpClient();
			HttpRequest httpRequest = HttpRequest.newBuilder()
										.uri(new URI("http://localhost:8080/myserver/api/demo/helloworld"))
										.GET()
										.build();
			CompletableFuture<HttpResponse<String>> httpResponse = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandler.asString());
			Thread.sleep(1000);
			if (httpResponse.isDone()) {
				HttpResponse<String> response = httpResponse.get();
				System.out.println("Status Code: " + response.statusCode());
				System.out.println("Content: " + response.body());
			} else {
				httpResponse.cancel(true);
				System.out.println("Request is taking more time, hence cancelling it");
			}
		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
		}

	}

}




Status Code: 200
Content: Hello World