From 80a6728abdd34d80495bfd18f0250bbf59865a25 Mon Sep 17 00:00:00 2001 From: Kaeso <24925519+ptlthg@users.noreply.github.com> Date: Sun, 27 Aug 2023 16:32:00 -0400 Subject: Merge pull request #335 * Sync Jacob Contests --- .../java/at/hannibal2/skyhanni/utils/APIUtil.kt | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'src/main/java/at/hannibal2/skyhanni/utils') diff --git a/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt b/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt index 04bd67c18..917243b47 100644 --- a/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt +++ b/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt @@ -7,6 +7,9 @@ import com.google.gson.JsonParser import com.google.gson.JsonSyntaxException import org.apache.http.client.config.RequestConfig import org.apache.http.client.methods.HttpGet +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity import org.apache.http.impl.client.HttpClientBuilder import org.apache.http.impl.client.HttpClients import org.apache.http.message.BasicHeader @@ -83,6 +86,38 @@ object APIUtil { return JsonObject() } + fun postJSONIsSuccessful(urlString: String, body: String, silentError: Boolean = false): Boolean { + val client = builder.build() + try { + val method = HttpPost(urlString) + method.entity = StringEntity(body, ContentType.APPLICATION_JSON) + + client.execute(method).use { response -> + val status = response.statusLine + + if (status.statusCode >= 200 || status.statusCode < 300) { + return true + } + + println("POST request to '$urlString' returned status ${status.statusCode}") + LorenzUtils.error("SkyHanni ran into an error whilst sending data. Status: ${status.statusCode}") + + return false + } + } catch (throwable: Throwable) { + if (silentError) { + throw throwable + } else { + throwable.printStackTrace() + LorenzUtils.error("SkyHanni ran into an ${throwable::class.simpleName ?: "error"} whilst sending a resource. See logs for more details.") + } + } finally { + client.close() + } + + return false + } + fun readFile(file: File): BufferedReader { return BufferedReader(InputStreamReader(FileInputStream(file), StandardCharsets.UTF_8)) } -- cgit