← Back to Advanced Java Course | Chapter 7: Networking & APIs | Lesson 3 of 4

Java का HTTP Client

HttpClient किसी Java program को websites से जानकारी मांगने देता है, जैसे एक request भेजना और reply पढ़ना। यह किसी server को data भेज भी सकता है।
Syntax
java
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

java
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());
	}
}

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

java
// 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());
	}
}

Asynchronous HTTP Requests

आप blocking send() के बजाय sendAsync() का उपयोग करके HTTP requests को asynchronously भेज सकते हैं। यह method तुरंत एक CompletableFuture return करता है, network call background में पूरा होने के दौरान आपके application को बाकी काम जारी रखने देते हुए बजाय किसी thread को I/O पर freeze करने के।

उदाहरण: Asynchronous HTTP Requests

java
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());
	}
}

POST Requests with BodyPublishers

POST request भेजने के लिए, यह define करने के लिए कि request body में क्या जाएगा एक BodyPublisher का उपयोग करें -- उदाहरण के लिए, JSON string सीधे भेजने के लिए ofString(), या किसी file के contents को पहले पूरी तरह memory में load किए बिना stream करने के लिए ofFile()।

उदाहरण: POST Requests with BodyPublishers

java
// 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");
	}
}

Managing Headers and Timeouts

आप अपने request builder पर सीधे standard headers (जैसे Content-Type या Authorization) जोड़ सकते हैं, और किसी धीमे या unresponsive server को आपके application को अनिश्चित काल तक hang करने से रोकने के लिए connection या request timeouts सेट कर सकते हैं।

उदाहरण: Managing Headers and Timeouts

java
// 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());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि 404 या 500 response एक exception फेंकता है, जबकि HttpClient इसे सामान्य रूप से return करता है और आपको response.statusCode() जांचना चाहिए।
  2. request पर timeout सेट न करना, जिससे एक धीमा server program को block कर सकता है।
  3. यह भूल जाना कि sendAsync एक CompletableFuture return करता है, इसलिए join() जैसा कुछ call न करना main को response आने से पहले खत्म होने देता है।
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.