-
Notifications
You must be signed in to change notification settings - Fork 0
/
RetrieveData.java
51 lines (41 loc) · 1.76 KB
/
RetrieveData.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class RetrieveData {
public static void main(String[] args) {
try {
// Specify the URL you want to retrieve data from
String urlString = "https://sohankafle.com.np";
URL url = new URL(urlString);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method (GET, POST, etc.)
connection.setRequestMethod("GET");
// Check the response code
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
// Create an InputStreamReader and BufferedReader to read the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
// Read the input line by line
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
// Close the BufferedReader
in.close();
// Print the retrieved content
System.out.println("Response Content: ");
System.out.println(content.toString());
} else {
System.out.println("GET request failed");
}
// Disconnect the connection
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}