apibase.tpl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package {{.}}
  2. import com.google.gson.Gson
  3. import kotlinx.coroutines.Dispatchers
  4. import kotlinx.coroutines.withContext
  5. import java.io.BufferedReader
  6. import java.io.InputStreamReader
  7. import java.io.OutputStreamWriter
  8. import java.net.HttpURLConnection
  9. import java.net.URL
  10. const val SERVER = "http://localhost:8080"
  11. suspend fun apiRequest(
  12. method: String,
  13. uri: String,
  14. body: Any = "",
  15. onOk: ((String) -> Unit)? = null,
  16. onFail: ((String) -> Unit)? = null,
  17. eventually: (() -> Unit)? = null
  18. ) = withContext(Dispatchers.IO) {
  19. val url = URL(SERVER + uri)
  20. with(url.openConnection() as HttpURLConnection) {
  21. connectTimeout = 3000
  22. requestMethod = method
  23. doInput = true
  24. if (method == "POST" || method == "PUT" || method == "PATCH") {
  25. setRequestProperty("Content-Type", "application/json; charset=utf-8")
  26. doOutput = true
  27. val data = when (body) {
  28. is String -> {
  29. body
  30. }
  31. else -> {
  32. Gson().toJson(body)
  33. }
  34. }
  35. val wr = OutputStreamWriter(outputStream)
  36. wr.write(data)
  37. wr.flush()
  38. }
  39. try {
  40. if (responseCode >= 400) {
  41. BufferedReader(InputStreamReader(errorStream)).use {
  42. val response = it.readText()
  43. onFail?.invoke(response)
  44. }
  45. return@with
  46. }
  47. //response
  48. BufferedReader(InputStreamReader(inputStream)).use {
  49. val response = it.readText()
  50. onOk?.invoke(response)
  51. }
  52. } catch (e: Exception) {
  53. e.message?.let { onFail?.invoke(it) }
  54. }
  55. }
  56. eventually?.invoke()
  57. }