From 9ebb4762b0e9ff54da20f95773378dc931999ee0 Mon Sep 17 00:00:00 2001 From: Roar Date: Tue, 3 Mar 2026 12:10:40 +0100 Subject: [PATCH] Updated APICharityScraper. Replaced the connection/get request logic to make it easier to mocktest with mockito. --- .../team6/models/APICharityScraper.java | 29 +++++++------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/helpmehelpapplication/src/main/java/ntnu/sytemutvikling/team6/models/APICharityScraper.java b/helpmehelpapplication/src/main/java/ntnu/sytemutvikling/team6/models/APICharityScraper.java index 27f2e60..8e93637 100644 --- a/helpmehelpapplication/src/main/java/ntnu/sytemutvikling/team6/models/APICharityScraper.java +++ b/helpmehelpapplication/src/main/java/ntnu/sytemutvikling/team6/models/APICharityScraper.java @@ -1,7 +1,6 @@ package ntnu.sytemutvikling.team6.models; import com.google.gson.Gson; - import java.io.IOException; import java.net.*; import java.net.http.HttpClient; @@ -12,35 +11,28 @@ import java.util.List; public class APICharityScraper { - private final URL url; - private HttpURLConnection connection; private final HttpClient client; private final HttpRequest request; - public APICharityScraper() throws IOException, URISyntaxException { - this.url = new URI("https://app.innsamlingskontrollen.no/api/public/v1/all").toURL(); - this.client = HttpClient.newHttpClient(); - this.connection = (HttpURLConnection) url.openConnection(); + + public APICharityScraper(HttpClient client) throws URISyntaxException { + this.client = client; this.request = HttpRequest.newBuilder() - .uri(url.toURI()) + .uri(new URI("https://app.innsamlingskontrollen.no/api/public/v1/all")) .GET() .build(); } // Checks whether a connection returns a get response - public boolean checkConnection() throws IOException { - this.connection = (HttpURLConnection) url.openConnection(); - this.connection.setRequestMethod("GET"); - this.connection.connect(); - - int response = this.connection.getResponseCode(); - String response_text = this.connection.getResponseMessage(); + public boolean checkConnection() throws IOException, InterruptedException { + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - if (response == 200) { + if (response.statusCode() == 200) { return true; } - throw new RuntimeException("Connection failed : HTTP error code : " + response + ". \n Response text: " + - response_text); + throw new RuntimeException("Connection failed: HTTP error code: " + response.statusCode() + + "\nResponse text: " + response.body() + ); } public String getJSONData() throws IOException, InterruptedException { @@ -49,6 +41,7 @@ public String getJSONData() throws IOException, InterruptedException { return response.body(); } + public List parseJSON(String JSONData) { Gson gson = new Gson(); APICharityData[] charityData = gson.fromJson(JSONData, APICharityData[].class);