Java का HTTP Client
In this page:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("url"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
HttpClient Introduction
Java 11 ने आज के web के लिए बना एक modern HttpClient class introduce किया। यह पुराने, अनाड़ी HttpURLConnection की जगह लेता है और HTTP/1.1 और HTTP/2 दोनों को seamlessly support करता है, connection reuse और server push जैसी features सहित जिन्हें पुराना API कभी अच्छी तरह handle नहीं कर पाया।
उदाहरण: HttpClient Introduction
import java.net.http.HttpClient;
public class Main {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient(); // supports HTTP/1.1 and HTTP/2
System.out.println(client.version());
}
}
Login to try C/C++/Java/PHP code in the editor
HttpRequest and HttpResponse
आप fluent HttpRequest.Builder API का उपयोग करके outgoing requests बनाते हैं और BodyHandlers का उपयोग करके responses parse करते हैं, जैसे text के लिए ofString() या बड़े payloads को stream करने के लिए ofInputStream()। यह builder pattern उन अजीब, mutable connection objects की जगह लेता है जिन्हें configure करने के लिए पुराना HttpURLConnection API मजबूर करता था।
उदाहरण: HttpRequest and HttpResponse
// Import java.net.http.HttpRequest so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.build();
// Print a line to the console
System.out.println(request.method() + " " + request.uri());
}
}
Login to try C/C++/Java/PHP code in the editor
Asynchronous HTTP Requests
आप blocking send() के बजाय sendAsync() का उपयोग करके HTTP requests को asynchronously भेज सकते हैं। यह method तुरंत एक CompletableFuture return करता है, network call background में पूरा होने के दौरान आपके application को बाकी काम जारी रखने देते हुए बजाय किसी thread को I/O पर freeze करने के।
उदाहरण: Asynchronous HTTP Requests
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "response body"); // like sendAsync() returning immediately
System.out.println(future.get());
}
}
Login to try C/C++/Java/PHP code in the editor
POST Requests with BodyPublishers
POST request भेजने के लिए, यह define करने के लिए कि request body में क्या जाएगा एक BodyPublisher का उपयोग करें -- उदाहरण के लिए, JSON string सीधे भेजने के लिए ofString(), या किसी file के contents को पहले पूरी तरह memory में load किए बिना stream करने के लिए ofFile()।
उदाहरण: POST Requests with BodyPublishers
// Import java.net.http.HttpRequest so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
.build();
// Print a line to the console
System.out.println(request.method() + " body publisher attached");
}
}
Login to try C/C++/Java/PHP code in the editor
Managing Headers and Timeouts
आप अपने request builder पर सीधे standard headers (जैसे Content-Type या Authorization) जोड़ सकते हैं, और किसी धीमे या unresponsive server को आपके application को अनिश्चित काल तक hang करने से रोकने के लिए connection या request timeouts सेट कर सकते हैं।
उदाहरण: Managing Headers and Timeouts
// Import java.net.http.HttpRequest so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
import java.time.Duration;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(5))
.build();
// Print a line to the console
System.out.println(request.headers().firstValue("Content-Type").get());
}
}
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि 404 या 500 response एक exception फेंकता है, जबकि
HttpClientइसे सामान्य रूप से return करता है और आपकोresponse.statusCode()जांचना चाहिए। - request पर timeout सेट न करना, जिससे एक धीमा server program को block कर सकता है।
- यह भूल जाना कि
sendAsyncएकCompletableFuturereturn करता है, इसलिएjoin()जैसा कुछ call न करनाmainको response आने से पहले खत्म होने देता है।
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: