HttpHelper.kt 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import android.graphics.Bitmap
  2. import android.graphics.BitmapFactory
  3. import org.json.JSONObject
  4. import java.io.*
  5. import java.net.HttpURLConnection
  6. import java.net.URL
  7. import java.net.URLEncoder
  8. import javax.net.ssl.HttpsURLConnection
  9. /*
  10. Перед использованием не забудьте добавить в манифест
  11. разрешение
  12. <uses-permission android:name="android.permission.INTERNET" />
  13. И атрибут в тег application
  14. android:usesCleartextTraffic="true"
  15. Использование:
  16. HTTP.requestGET(
  17. "http://s4a.kolei.ru/Product",
  18. mapOf(
  19. "token" to token
  20. )
  21. ){result, error ->
  22. runOnUiThread{
  23. if(result!=null){
  24. resultTextView.text = result
  25. }
  26. else
  27. AlertDialog.Builder(this)
  28. .setTitle("Ошибка http-запроса")
  29. .setMessage(error)
  30. .setPositiveButton("OK", null)
  31. .create()
  32. .show()
  33. }
  34. }
  35. HTTP.requestPOST(
  36. "http://s4a.kolei.ru/login",
  37. JSONObject().put("username", username).put("password", password),
  38. mapOf(
  39. "Content-Type" to "application/json"
  40. )
  41. ){result, error ->
  42. runOnUiThread{
  43. if(result!=null){
  44. }
  45. else
  46. AlertDialog.Builder(this)
  47. .setTitle("Ошибка http-запроса")
  48. .setMessage(error)
  49. .setPositiveButton("OK", null)
  50. .create()
  51. .show()
  52. }
  53. }
  54. HTTP.getImage("https://openweathermap.org/img/w/${icoName}.png") { bitmap, error ->
  55. runOnUiThread {
  56. if (bitmap != null) {
  57. var imageView = findViewById<ImageView>(R.id.ico)
  58. imageView.setImageBitmap(bitmap)
  59. }
  60. }
  61. }
  62. */
  63. object HTTP
  64. {
  65. private const val GET : String = "GET"
  66. private const val POST : String = "POST"
  67. /**
  68. * Метод для отправки POST-запросов
  69. *
  70. * Запросы отправляются в отдельном потоке
  71. * Автоматически поддерживает http/httpS
  72. * Можно задать заголовки запроса
  73. * По-умолчанию отправляет данные в формате application/x-www-form-urlencoded
  74. * при задании заголовка Content-type: application/json автоматически переключается на это тип
  75. *
  76. * @param url Полный URL сайта (протокол + домен + путь)
  77. * @param postData Даные для отправки
  78. * @param headers Ассоциативный массив заголовков запроса
  79. * @param callback Лямбда-функция обратного вызова
  80. */
  81. fun requestPOST(
  82. url: String,
  83. postData: JSONObject? = null,
  84. headers: Map<String, String>?,
  85. callback: (result: String?, error: String)->Unit
  86. ) {
  87. Thread( Runnable {
  88. var error = ""
  89. var result: String? = null
  90. try {
  91. val urlURL = URL(url)
  92. val conn: HttpURLConnection = if (url.startsWith("https:", true))
  93. urlURL.openConnection() as HttpsURLConnection
  94. else
  95. urlURL.openConnection() as HttpURLConnection
  96. // если задан тип контента application/json, то на выход пишу как есть
  97. var contentTypeJson = false
  98. if(headers!=null){
  99. for((key, value) in headers){
  100. if(key.lowercase()=="content-type" && value.startsWith("application/json"))
  101. contentTypeJson = true
  102. conn.setRequestProperty(key, value)
  103. }
  104. }
  105. conn.readTimeout = 10000
  106. conn.connectTimeout = 10000
  107. conn.requestMethod = POST
  108. conn.doInput = true
  109. conn.doOutput = true
  110. val os: OutputStream = conn.outputStream
  111. if (postData != null) {
  112. val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8"))
  113. var content = ""
  114. content = if(contentTypeJson)
  115. postData.toString()
  116. else
  117. encodeParams(postData)?:""
  118. writer.write(content)
  119. writer.flush()
  120. writer.close()
  121. }
  122. os.close()
  123. val responseCode: Int = conn.responseCode // To Check for 200
  124. if (responseCode == HttpsURLConnection.HTTP_OK) {
  125. val `in` = BufferedReader(InputStreamReader(conn.inputStream))
  126. val sb = StringBuffer("")
  127. var line: String? = ""
  128. while (`in`.readLine().also { line = it } != null) {
  129. sb.append(line)
  130. break
  131. }
  132. `in`.close()
  133. result = sb.toString()
  134. }
  135. else {
  136. error = "Response code ${responseCode}"
  137. }
  138. }
  139. catch (e: Exception) {
  140. error = e.message.toString()
  141. }
  142. callback.invoke(result, error)
  143. }).start()
  144. }
  145. fun getImage(url: String, callback: (result: Bitmap?, error: String)->Unit){
  146. Thread( Runnable {
  147. var image: Bitmap? = null
  148. var error = ""
  149. try {
  150. val `in` = URL(url).openStream()
  151. image = BitmapFactory.decodeStream(`in`)
  152. }
  153. catch (e: Exception) {
  154. error = e.message.toString()
  155. }
  156. callback.invoke(image, error)
  157. }).start()
  158. }
  159. fun requestGET(
  160. r_url: String,
  161. headers: Map<String, String>?,
  162. callback: (result: String?, error: String)->Unit
  163. ) {
  164. Thread( Runnable {
  165. var error = ""
  166. var result: String? = null
  167. try {
  168. val obj = URL(r_url)
  169. val con: HttpURLConnection = if(r_url.startsWith("https:", true))
  170. obj.openConnection() as HttpsURLConnection
  171. else
  172. obj.openConnection() as HttpURLConnection
  173. if(headers!=null){
  174. for((key, value) in headers){
  175. con.setRequestProperty(key, value)
  176. }
  177. }
  178. con.requestMethod = GET
  179. val responseCode = con.responseCode
  180. result = if (responseCode == HttpURLConnection.HTTP_OK) { // connection ok
  181. val `in` =
  182. BufferedReader(InputStreamReader(con.inputStream))
  183. var inputLine: String?
  184. val response = StringBuffer()
  185. while (`in`.readLine().also { inputLine = it } != null) {
  186. response.append(inputLine)
  187. }
  188. `in`.close()
  189. response.toString()
  190. } else {
  191. null
  192. }
  193. }
  194. catch (e: Exception){
  195. error = e.message.toString()
  196. }
  197. callback.invoke(result, error)
  198. }).start()
  199. }
  200. @Throws(IOException::class)
  201. private fun encodeParams(params: JSONObject): String? {
  202. val result = StringBuilder()
  203. var first = true
  204. val itr = params.keys()
  205. while (itr.hasNext()) {
  206. val key = itr.next()
  207. val value = params[key]
  208. if (first) first = false else result.append("&")
  209. result.append(URLEncoder.encode(key, "UTF-8"))
  210. result.append("=")
  211. result.append(URLEncoder.encode(value.toString(), "UTF-8"))
  212. }
  213. return result.toString()
  214. }
  215. }