The HTTP Client in Java provides an easy way to send HTTP requests and handle responses. It supports both synchronous and asynchronous processing, making it suitable for various applications. The API is designed to work seamlessly with both HTTP/1.1 and HTTP/2 protocols.
This modern client is part of the Java standard library, starting from Java 11, and offers a more flexible and efficient means of interacting with web services compared to the older `HttpURLConnection` class.
// Import required classes
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class HttpClientExample {
public static void main(String[] args) {
// Create HttpClient
HttpClient client = HttpClient.newHttpClient();
// Create HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/data"))
.timeout(Duration.ofMinutes(1))
.build();
// Send request and get response
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?