http client request java code example

Example 1: http client java

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("http://openjdk.java.net/"))
      .build();
client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

Example 2: java http request

// open a connection, the request method is "GET" by default
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");

// you can use one of these methods to get the results
connection.connect();
connection.getResponseCode();
connection.getInputStream();
connection.getOutputStream();

// close the connection
connection.disconnect();

Tags:

Java Example