package models; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Scanner; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class RestClient { private String host = "http://localhost:8000/api/"; public InputStream getDataAsStream() { InputStream inputStream = null; try { inputStream = tryGetDataAsStream(); } catch (MalformedURLException e) { System.err.println("Hiba! Az url nem jó"); }catch (IOException e) { System.err.println("Hiba! A lekérés sikertelen"); } return inputStream; } public InputStream tryGetDataAsStream() throws MalformedURLException, IOException{ String endpoint = "employees"; String urlStr = host + endpoint; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); int response = conn.getResponseCode(); if(response != HttpURLConnection.HTTP_OK) { throw new RuntimeException("HttpResponseCode:" + response); }else { return url.openStream(); } } public String getDataAsString(InputStream inputStream) { Scanner sc = new Scanner(inputStream, "UTF-8"); String content = ""; while(sc.hasNext()) { content += sc.nextLine(); } sc.close(); return content; } public ArrayList getEmployeeAsArray(String content) { ArrayList list = null; try { list = tryGetEmployeeAsArray(content); }catch(ParseException e) { System.err.println("Hiba! Az értelmezés sikertelen!"); } return list; } public ArrayList tryGetEmployeeAsArray(String content) throws ParseException { JSONParser parser = new JSONParser(); Object obj = parser.parse(content); JSONArray ja = (JSONArray) obj; ArrayList list = new ArrayList<>(); for(int i=0; i getEmployees() { InputStream inputStream = this.getDataAsStream(); String content = this.getDataAsString(inputStream); return getEmployeeAsArray(content); } }