From 16d309e1e5483b5083671b550f33394604c475cf Mon Sep 17 00:00:00 2001 From: binsky Date: Sat, 5 Feb 2022 16:56:55 +0100 Subject: [PATCH] implement simple http api to make get requests --- src/main/java/HttpApi.java | 27 +++++++++++++++++++++++++++ src/test/java/HttpApiTest.java | 19 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/main/java/HttpApi.java create mode 100644 src/test/java/HttpApiTest.java 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(); + } + } +}