I'm new to Kotlin and Android developing. I'm trying to use the HttpsURL to POST a value of '0' or any other value to the 'data' variable https://www.mytestsite.com/on-test.php where is a 'data' variable set inside.
My Kotlin code is reaching the '../on-php' url but the POST method is likely not executed or no data was transferred for some unknown reason. I also made another 'post.php' from where I'm posting to the same on-test.php like my Android app, and that way it is working. I have no any idea what I'm doing wrong. Any help I would appreciate.
Here is my code I'm trying to make working:
btn_test.setOnClickListener {
object : AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void?): Void? {
val url = "https://www.mytestsite.com/on-test.php"
val data = JSONObject()
data.put("data", "0")
val connection = URL(url).openConnection() as HttpsURLConnection
connection.requestMethod = "POST"
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json")
connection.connect()
val wr = DataOutputStream(connection.outputStream)
wr.writeBytes(data.toString())
wr.flush()
wr.close()
error_data = connection.responseMessage
return null
}
}.execute()
text_status.setText(error_data)
}
CodePudding user response:
To make a HTTP POST request in Kotlin, you can use the HttpURLConnection class or a library such as Retrofit. Here's an example using HttpURLConnection:
btn_test.setOnClickListener {
val url = URL("https://www.mytestsite.com/on-test.php")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.doOutput = true
connection.doInput = true
connection.setRequestProperty("Content-Type", "application/json")
val json = """
{
"key1": "value1",
"key2": "value2"
}
""".trimIndent()
val outputStream = connection.outputStream
outputStream.write(json.toByteArray(Charsets.UTF_8))
outputStream.flush()
outputStream.close()
val responseCode = connection.responseCode
if (responseCode == 200) {
val inputStream = connection.inputStream
val response = inputStream.bufferedReader().use { it.readText() }
println(response)
} else {
println("Error, response code: $responseCode")
}
}
CodePudding user response:
Here's an example of using Kotlin coroutines to make an asynchronous network request:
Step1 :Start by creating a Retrofit service interface for your API endpoint. This defines the endpoint you want to call and the expected data format for the request and response.
interface ApiService {
@POST("/api/endpoint")
suspend fun makePostRequest(@Body request: RequestBody): Response<ResponseBody>
}
Step 2: Implement the Retrofit service interface in your ViewModel. This is where you will make the network request. You can use the viewModelScope to launch a coroutine and make the API call.
class MyViewModel : ViewModel() {
private val apiService = Retrofit.Builder()
.baseUrl("https://www.mytestsite.com/on-test.php")
.build()
.create(ApiService::class.java)
private val _response = MutableLiveData<String>()
val response: LiveData<String>
get() = _response
fun makeApiCall(requestBody: RequestBody) {
viewModelScope.launch {
val response = apiService.makePostRequest(requestBody)
if (response.isSuccessful) {
_response.value = response.body()?.string()
} else {
_response.value = response.errorBody()?.string()
}
}
}
}
Step 3: In your Fragment or Activity, observe the response LiveData. This allows you to react to changes in the data and update the UI accordingly.
viewModel.response.observe(this, Observer { response ->
// update UI with response
})
Finally, call the makeApiCall method from your Fragment or Activity, passing in the necessary parameters for your API call.
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
"{\"key\":\"value\"}"
)
viewModel.makeApiCall(requestBody)
The example is making a POST request to an API endpoint with a JSON payload. The response from the API is stored in a MutableLiveData, which can be observed by a Fragment or Activity to update the UI with the latest data.