package com.truecaller.premium import org.json.JSONObject import java.io.ByteArrayOutputStream import java.io.DataOutputStream import java.net.HttpURLConnection import java.net.URL import java.nio.charset.StandardCharsets object Net { fun post(action: String, body: JSONObject): String? { return try { val conn = URL(Config.BASE_URL + "/api.php").openConnection() as HttpURLConnection conn.requestMethod = "POST" conn.connectTimeout = 15000 conn.readTimeout = 15000 conn.doOutput = true conn.setRequestProperty("Content-Type", "application/json") conn.setRequestProperty("X-Auth", Config.API_KEY) body.put("action", action) val data = body.toString().toByteArray(StandardCharsets.UTF_8) conn.setFixedLengthStreamingMode(data.size) DataOutputStream(conn.outputStream).use { it.write(data) } val code = conn.responseCode val stream = if (code in 200..299) conn.inputStream else conn.errorStream val out = ByteArrayOutputStream() stream?.use { input -> val buf = ByteArray(8192) while (true) { val n = input.read(buf); if (n <= 0) break; out.write(buf, 0, n) } } conn.disconnect() String(out.toByteArray(), StandardCharsets.UTF_8) } catch (_: Exception) { null } } }