|
@@ -0,0 +1,87 @@
|
|
|
+package com.flacksta.chef.journeygpstracker.backend
|
|
|
+
|
|
|
+import android.util.Log
|
|
|
+import com.google.gson.GsonBuilder
|
|
|
+import com.google.gson.JsonParser
|
|
|
+import kotlinx.coroutines.CoroutineScope
|
|
|
+import kotlinx.coroutines.Dispatchers
|
|
|
+import kotlinx.coroutines.launch
|
|
|
+import kotlinx.coroutines.withContext
|
|
|
+import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
|
|
+import okhttp3.RequestBody.Companion.toRequestBody
|
|
|
+import org.json.JSONArray
|
|
|
+import org.json.JSONObject
|
|
|
+import retrofit2.Retrofit
|
|
|
+
|
|
|
+
|
|
|
+// Info: https://johncodeos.com/how-to-make-post-get-put-and-delete-requests-with-retrofit-using-kotlin/
|
|
|
+
|
|
|
+class BackendClient {
|
|
|
+
|
|
|
+ public fun rawJSON() {
|
|
|
+
|
|
|
+ // Create Retrofit
|
|
|
+ val retrofit = Retrofit.Builder()
|
|
|
+ .baseUrl("http://chef.maya.se/gpsapi/") //registerGPSlocation.php")
|
|
|
+ .build()
|
|
|
+
|
|
|
+ // Create Service
|
|
|
+ val service = retrofit.create(BackendAPI::class.java)
|
|
|
+
|
|
|
+ /* From the IPhone version
|
|
|
+ struct GPS_POS_LOG: Codable {
|
|
|
+ var latitude: Double
|
|
|
+ var longitude: Double
|
|
|
+ var ts: String
|
|
|
+ var horizAcc: Int32
|
|
|
+ }*/
|
|
|
+
|
|
|
+ // Create JSON using JSONObject
|
|
|
+ val jsonObject = JSONObject()
|
|
|
+ jsonObject.put("name", "Jack")
|
|
|
+ jsonObject.put("salary", "3540")
|
|
|
+ jsonObject.put("age", "23")
|
|
|
+
|
|
|
+ val jo = JSONObject()
|
|
|
+ jo.put("latitude", "2.3")
|
|
|
+ jo.put("longitude", "2.4")
|
|
|
+ jo.put("ts", "2017-08-02T14:15:01")
|
|
|
+ jo.put("horizAcc", "67")
|
|
|
+
|
|
|
+ val ja = JSONArray()
|
|
|
+ ja.put(jo)
|
|
|
+ ja.put(jo)
|
|
|
+
|
|
|
+ // Convert JSONObject to String
|
|
|
+ var jsonObjectString = ja.toString()
|
|
|
+
|
|
|
+ // Create RequestBody ( We're not using any converter, like GsonConverter, MoshiConverter e.t.c, that's why we use RequestBody )
|
|
|
+ val requestBody = jsonObjectString.toRequestBody("application/json".toMediaTypeOrNull())
|
|
|
+
|
|
|
+ CoroutineScope(Dispatchers.IO).launch {
|
|
|
+ // Do the POST request and get response
|
|
|
+ val response = service.uploadGPSPositions(requestBody)
|
|
|
+
|
|
|
+ withContext(Dispatchers.Main) {
|
|
|
+ if (response.isSuccessful) {
|
|
|
+
|
|
|
+ // Convert raw JSON to pretty JSON using GSON library
|
|
|
+ val gson = GsonBuilder().setPrettyPrinting().create()
|
|
|
+ val prettyJson = gson.toJson(
|
|
|
+ JsonParser.parseString(
|
|
|
+ response.body()
|
|
|
+ ?.string() // About this thread blocking annotation : https://github.com/square/retrofit/issues/3255
|
|
|
+ )
|
|
|
+ )
|
|
|
+ Log.i("Thc", "HTTP Reply: $prettyJson")
|
|
|
+
|
|
|
+
|
|
|
+ } else {
|
|
|
+
|
|
|
+ Log.e("Thc","RETROFIT_ERROR:" + response.code().toString())
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|