كيفية إجراء طلب HTTP في Java؟
مرحباً بالجميع! من فضلكم، أخبروني كيف يمكنني تنفيذ طلب HTTP (GET و POST) بشكل صحيح في Java الخالصة دون استخدام مكتبات خارجية مثل Apache HttpClient أو OkHttp. أنا مبتدئ في Java وأحاول فهم طلبات الشبكة.
حاولت استخدام الكلاس HttpURLConnection من الحزمة java.net، لكني واجهت مشاكل. إليك الكود الخاص بي لطلب GET:
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.clos