I'm trying to get some things from my api which works well on Andoird with Kotlin.
I uses a solution without Volley or something so. It worked till yesterday as I added the try...catch. Now the API just return the message saying ther is no post parametres. Could you have a look at my code and tell me what I did wrong ?
Thanks a lot !
fun recupCasesBDDExt(url: String) {
try {
val reqParam = URLEncoder.encode("demande", "UTF-8") + "=" + URLEncoder.encode("cases", "UTF-8")
var reponseJson = JSONObject("{}")
val mURL = URL(url)
with(mURL.openConnection() as HttpURLConnection) {
requestMethod = "POST"
val wr = OutputStreamWriter(outputStream)
wr.write(reqParam)
wr.flush()
BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
reponseJson = JSONObject(response.toString())
}
}
Log.i("reponseJson", reponseJson.toString())
if (!reponseJson.getBoolean("error")) {
cases.removeAll { true }
val casesBddExt = reponseJson.getJSONArray("cases")
/* You don't need to read it. The problem comes from earlier.
for (i in 0 until casesBddExt.length()) {
val nouvElement = casesBddExt[i] as JSONObject
val case = Case(
nouvElement["id"].toString().toLong(),
nouvElement["nom"].toString(),
nouvElement["nomCourt"].toString(),
nouvElement["couleur"].toString().toInt(),
nouvElement["couleurTexte"].toString().toInt(),
nouvElement["prix"].toString().toDouble(),
nouvElement["ordre"].toString().toInt()
)
cases.add(case)
cases.sortBy { it.ordre }
val bdd = Room.databaseBuilder(context!!, MaBdd::class.java, "Case").build()
bdd.caseDao().apply {
this.empty()
this.insertAll(cases)
}
bdd.close()
val bddH = Room.databaseBuilder(context!!, MaBdd::class.java, "historique").build()
bddH.historiqueDao().apply {
this.empty()
}
bddH.close()
}
*/
}
} catch (e: Exception) {
context!!.longToast("L'url $url n'a pas été trouvé.")
e.printStackTrace()
}
}
My sample was the post of Deven on this topic : HTTP Request in Kotlin
EDIT : I forgot to say that this function is called from an asyncronious task so no error is thrown with this code. It just doesn't send the post parameters to the API.
No comments:
Post a Comment