Answer the question
In order to leave comments, you need to log in
Android HttpURLConnection not passing data?
The connection comes to the computer, but the NodeJS server does not react to it in any way.
There are no problems with the server.
package com.ds.da.sensorsurvey
import android.os.AsyncTask
import java.io.BufferedOutputStream
import java.io.BufferedWriter
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL
class CallAPI () : AsyncTask<String, String, String>() {
override fun onPreExecute() {
super.onPreExecute()
}
override fun doInBackground(vararg params: String): String? {
val urlString = params[0] // URL to call
val data = params[1] //data to post
var out: OutputStream? = null
try {
val url = URL(urlString)
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = "POST"
urlConnection.setRequestProperty("Content-Type", "application/json")
out = BufferedOutputStream(urlConnection.outputStream)
BufferedWriter(OutputStreamWriter(out, "UTF-8")).use{
it.write(data)
it.flush()
}
out!!.close()
urlConnection.connect()
} catch (e: Exception) {
println(e.message)
}
return null
}
}
Answer the question
In order to leave comments, you need to log in
I think that you first need to connect, and only then write data to the stream. IMHO, that's the problem.
Well, comments in general. AsyncTask should not be used for the network. This will end badly.
HttpUrlConnection has, as you can see, a very bad API.
It's better to take OkHttp and use it. It will be smarter and prettier. And more opportunities.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question