diff --git a/src/main/java/HttpApi.java b/src/main/java/HttpApi.java new file mode 100644 index 0000000..1e3beef --- /dev/null +++ b/src/main/java/HttpApi.java @@ -0,0 +1,27 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +public class HttpApi { + public static String sendHttpGETRequest(String url) throws IOException { + URL obj = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection(); + httpURLConnection.setRequestMethod("GET"); + int responseCode = httpURLConnection.getResponseCode(); + + if (responseCode == HttpURLConnection.HTTP_OK) { + BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); + + while ((inputLine = in .readLine()) != null) { + response.append(inputLine); + } in .close(); + + return response.toString(); + } + return null; + } +} diff --git a/src/test/java/HttpApiTest.java b/src/test/java/HttpApiTest.java new file mode 100644 index 0000000..56aa6da --- /dev/null +++ b/src/test/java/HttpApiTest.java @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.*; + +class HttpApiTest { + + @Test + void sendHttpGETRequest() { + assertDoesNotThrow(() -> HttpApi.sendHttpGETRequest("https://httpbin.org/get")); + try { + assertTrue(Objects.requireNonNull(HttpApi.sendHttpGETRequest("https://httpbin.org/get")).contains("args")); + } catch (IOException e) { + e.printStackTrace(); + } + } +}