Answer the question
In order to leave comments, you need to log in
Android how to send a post request?
Hello everyone, I'm trying to send a post request to the server using android. 1000 options and only a few manage to launch.
I found the Fuel library, supposedly the best of the best)) Here is a small example of their code.
Fuel.post("https://httpbin.org/post")
.jsonBody("{ \"foo\" : \"bar\" }")
.also { println(it) }
.response { result -> }
<?
print_r($_POST);
?>
.jsonBody("{ \"foo\" : \"bar\" }")
.jsonBody("foo=bar")
.body("{ \"foo\" : \"bar\" }")
.body("foo=bar")
fun sendPostRequest(userName:String, password:String) {
var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")
val mURL = URL("http://.../test.php")
with(mURL.openConnection() as HttpURLConnection) {
// optional default is GET
requestMethod = "POST"
val wr = OutputStreamWriter(getOutputStream());
wr.write(reqParam);
wr.flush();
Log.i(App.TAG,"URL : $url")
Log.i(App.TAG,"Response Code : $responseCode")
BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
Log.i(App.TAG,"Response : $response")
}
wr.close()
}
}
dependencies {
implementation 'androidx.leanback:leanback:1.0.0'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.work:work-runtime-ktx:2.5.0'
implementation 'androidx.tvprovider:tvprovider:1.0.0'
implementation 'androidx.preference:preference-ktx:1.1.1'
//Update
implementation 'com.g00fy2:versioncompare:1.2.8'
//Network
implementation "com.google.code.gson:gson:2.8.6"
implementation 'com.github.kittinunf.fuel:fuel:2.3.1'
implementation 'com.github.kittinunf.fuel:fuel-gson:2.3.1'
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question