java.net.URL क्लास वेब संसाधनों से डेटा पढ़ने का एक सरल तरीका प्रदान करती है।
पढ़ने के चरण
URLऑब्जेक्ट बनाएं:new URL("https://example.com")openStream()के माध्यम सेInputStreamखोलेंScanner,BufferedReader, याInputStreamReaderमें लपेटें- डेटा पढ़ें
- स्ट्रीम बंद करें
उदाहरण
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadWebPage {
public static void main(String args[]) throws IOException {
URL url = new URL("https://www.example.com/");
try (Scanner sc = new Scanner(url.openStream())) {
StringBuilder sb = new StringBuilder();
while (sc.hasNext()) {
sb.append(sc.next());
}
String result = sb.toString();
System.out.println("Raw HTML: " + result);
// HTML टैग हटाएं (सरल)
result = result.replaceAll("<[^>]*>", "");
System.out.println("Text content: " + result);
}
}
}आउटपुट
Raw HTML:It works!
Text content: It works!
लिखने के लिए (HTTP POST)
HttpURLConnection का उपयोग करें:
URL url = new URL("https://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write("param=value".getBytes());
}
int responseCode = conn.getResponseCode();सर्वोत्तम अभ्यास
- हमेशा try-with-resources का उपयोग करें।
- टाइमआउट सेट करें:
conn.setConnectTimeout(5000)। - उत्पादन के लिए Apache HttpClient या OkHttp जैसे उच्च-स्तरीय लाइब्रेरी पर विचार करें।