HttpHelper.kt 4.2 KB

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