HttpHelper.kt 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package ru.yotc.myapplication
  2. import android.graphics.Bitmap
  3. import android.graphics.BitmapFactory
  4. import org.json.JSONObject
  5. import java.io.*
  6. import java.net.HttpURLConnection
  7. import java.net.URL
  8. import java.net.URLEncoder
  9. import javax.net.ssl.HttpsURLConnection
  10. /*
  11. Перед использованием не забудьте добавить в манифест
  12. разрешение
  13. <uses-permission android:name="android.permission.INTERNET" />
  14. И атрибут в тег application
  15. android:usesCleartextTraffic="true"
  16. */
  17. object HTTP
  18. {
  19. private const val GET : String = "GET"
  20. private const val POST : String = "POST"
  21. /*
  22. @Throws(IOException::class)
  23. fun requestPOST(r_url: String, postDataParams: JSONObject): String? {
  24. val url = URL(r_url)
  25. val conn: HttpURLConnection = if(r_url.startsWith("https:", true))
  26. url.openConnection() as HttpsURLConnection
  27. else
  28. url.openConnection() as HttpURLConnection
  29. conn.readTimeout = 3000
  30. conn.connectTimeout = 3000
  31. conn.requestMethod = POST
  32. conn.doInput = true
  33. conn.doOutput = true
  34. val os: OutputStream = conn.outputStream
  35. val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8"))
  36. writer.write(encodeParams(postDataParams))
  37. writer.flush()
  38. writer.close()
  39. os.close()
  40. val responseCode: Int = conn.responseCode // To Check for 200
  41. if (responseCode == HttpsURLConnection.HTTP_OK) {
  42. val `in` = BufferedReader(InputStreamReader(conn.inputStream))
  43. val sb = StringBuffer("")
  44. var line: String? = ""
  45. while (`in`.readLine().also { line = it } != null) {
  46. sb.append(line)
  47. break
  48. }
  49. `in`.close()
  50. return sb.toString()
  51. }
  52. return null
  53. }
  54. */
  55. fun getImage(url: String, callback: (result: Bitmap?, error: String)->Unit){
  56. Thread( Runnable {
  57. var image: Bitmap? = null
  58. var error = ""
  59. try {
  60. val `in` = URL(url).openStream()
  61. image = BitmapFactory.decodeStream(`in`)
  62. }
  63. catch (e: Exception) {
  64. error = e.message.toString()
  65. }
  66. callback.invoke(image, error)
  67. }).start()
  68. }
  69. fun requestGET(r_url: String, callback: (result: String?, error: String)->Unit) {
  70. Thread( Runnable {
  71. var error = ""
  72. var result: String? = null
  73. try {
  74. val obj = URL(r_url)
  75. val con: HttpURLConnection = if(r_url.startsWith("https:", true))
  76. obj.openConnection() as HttpsURLConnection
  77. else
  78. obj.openConnection() as HttpURLConnection
  79. con.requestMethod = GET
  80. val responseCode = con.responseCode
  81. result = if (responseCode == HttpURLConnection.HTTP_OK) { // connection ok
  82. val `in` =
  83. BufferedReader(InputStreamReader(con.inputStream))
  84. var inputLine: String?
  85. val response = StringBuffer()
  86. while (`in`.readLine().also { inputLine = it } != null) {
  87. response.append(inputLine)
  88. }
  89. `in`.close()
  90. response.toString()
  91. } else {
  92. null
  93. }
  94. }
  95. catch (e: Exception){
  96. error = e.message.toString()
  97. }
  98. callback.invoke(result, error)
  99. }).start()
  100. }
  101. @Throws(IOException::class)
  102. private fun encodeParams(params: JSONObject): String? {
  103. val result = StringBuilder()
  104. var first = true
  105. val itr = params.keys()
  106. while (itr.hasNext()) {
  107. val key = itr.next()
  108. val value = params[key]
  109. if (first) first = false else result.append("&")
  110. result.append(URLEncoder.encode(key, "UTF-8"))
  111. result.append("=")
  112. result.append(URLEncoder.encode(value.toString(), "UTF-8"))
  113. }
  114. return result.toString()
  115. }
  116. }