From cc41445d2f125435d82e5a261032388f8a1d162c Mon Sep 17 00:00:00 2001 From: moonleay Date: Thu, 5 Oct 2023 11:39:46 +0200 Subject: [PATCH] feat: added NetUtil for web requests Signed-off-by: moonleay --- .../net/moonleay/lilJudd/util/NetUtil.kt | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/kotlin/net/moonleay/lilJudd/util/NetUtil.kt diff --git a/src/main/kotlin/net/moonleay/lilJudd/util/NetUtil.kt b/src/main/kotlin/net/moonleay/lilJudd/util/NetUtil.kt new file mode 100644 index 0000000..5b43bbc --- /dev/null +++ b/src/main/kotlin/net/moonleay/lilJudd/util/NetUtil.kt @@ -0,0 +1,45 @@ +/* + * lilJudd + * Copyright (C) 2023 moonleay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.moonleay.lilJudd.util + +import java.net.URL +import javax.net.ssl.HttpsURLConnection + +object NetUtil { + fun GETJsonData(urlIN: String, userAgent: String): String { + val startTime = System.currentTimeMillis() + val url = URL(urlIN) + val connection = url.openConnection() as HttpsURLConnection + connection.requestMethod = "GET" + connection.setRequestProperty("User-Agent", userAgent) + connection.setRequestProperty("Accept", "application/json") + val responseCode = connection.responseCode + val timeDiff = System.currentTimeMillis() - startTime + Logger.out("GET took $timeDiff ms (from: $urlIN, as $userAgent)") + return if (responseCode == HttpsURLConnection.HTTP_OK) { + val inputStream = connection.inputStream + val inputStreamReader = inputStream.reader() + val inputAsString = inputStreamReader.readText() + inputStream.close() + inputAsString + } else { + "Error $responseCode" + } + } +}