feat: added NetUtil for web requests

Signed-off-by: moonleay <contact@moonleay.net>
This commit is contained in:
moonleay 2023-10-05 11:39:46 +02:00
parent b08779546d
commit cc41445d2f

View file

@ -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 <https://www.gnu.org/licenses/>.
*/
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"
}
}
}