2024-11-19 10:45:50 +01:00

40 lines
1.0 KiB
Java

package eirb.pg203.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONFetcher {
private static String fetchString(URL url) throws IOException{
StringBuilder result = new StringBuilder();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
for (String line; (line = reader.readLine()) != null; ) {
result.append(line);
}
}
return result.toString();
}
public static JSONObject fetch(URL url) throws IOException {
String result = fetchString(url);
return new JSONObject(result);
}
public static JSONArray fetchArray(URL url) throws IOException {
String result = fetchString(url);
return new JSONArray(result);
}
}