How to POST multipart/form-data using Fuel for Kotlin? - android

I need to send a POST request to a server. I'm supposed to pass some parameters and an image. I am able to do this from Postman, but I can't do this on my Android app (latest SDK) using Fuel.
This is the code I'm using:
val formData = listOf("name" to "name")
val (_, _, result) = Fuel.upload("http://10.0.2.2:3000/test", parameters = formData)
.source { request, url -> imageFile } // type is File
.responseObject<CustomResponse>()
This is the postman screenshot:
I don't have access to the backend code, just some logs. It seems the request body is empty and the file also doesn't get uploaded. How can I do this? I'm at a loss.
I also tried passing the parameters as a jsonBody, this does submit the body, but the content type is not multipart/form-data and the image is still missing.
This JS code works:
let formData = new FormData();
formData.append('name', 'name');
formData.append('image', this.file);
axios.post(`${API_URL}/test`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(console.log).catch(console.log)
Edit: I also tried passing the file as a DataPart, still nothing.

After some struggle I found out what would work:
val file = FileDataPart.from("path_to_your_file", name = "image")
val (_, _, result) = Fuel.upload("http://10.0.2.2:3000/test")
.add(file)
.responseObject<CustomResponse>()
I didn't need name-name part in my case but I would try to add InlineDataPart

After some try finally I found the solution.
Try this I think it will help.
val params = listOf("email" to "test#email.com", "pass" to "123456")
Fuel.upload("http://your-api-url.com/login", Method.POST, params)
.responseString { _, _, result ->
when (result) {
is Result.Failure -> {
print(result.getException().toString())
}
is Result.Success -> {
val data = result.get()
print(data)
}
}
}

I managed to send a POST request to a server. I passed a parameter and an image.
//Prepare POST body
val postBody = listOf("name" to "name")
//Call the API.
val (_, _, result) = Fuel.upload("http://10.0.2.2:3000/test", Method.POST , postBody)
.add(BlobDataPart(myInputStream, name = "image", filename = "default.jpg", contentType = "image/jpeg"))
.responseString()
//If failed, then print exception. If successful, then print result.
when (result) {
is Result.Failure -> {
println(result.getException())
}
is Result.Success -> {
println(result.get())
}
}
You can read the related documentation here.

Related

How to prevent Ktor Client from encoding url parameters?

I am trying to create an android app with kotlin, this app need to have a mini download manager as I will need to download files from 100MB to 8GB and user can pause and resume download later when the server supports the pause, searching I found the Ktor library and reading the documentation plus some videos on youtube, I managed to write a base code where I could download the files and make the process of stopping the download and keep going all right when one of mine tests gave error there are files whose url pattern is: http://server.com/files?file=/10/55/file.zip
The problem is that I put this link, but Ktor converts to http://server.com/files?file=%2F10%2F55%2Ffile.zip this generate an error response on the server, as I don't have access to the server to change this rule I need to send the right url without encoding. Does anyone know how to do this? Prevent Ktor from doing a URL_encode in the url parameters, I couldn't find anything in the documentation
My code is this:
ktor-client version 1.6.7
fun startDownload(url: String, auth: String = "", userAgentS: String = "", fileName: String = ""){
val client = HttpClient(CIO)
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val file = File.createTempFile("File", "index", path)
runBlocking {
client.get<HttpStatement>(url){
headers {
append(HttpHeaders.Authorization, auth)
append(HttpHeaders.UserAgent, userAgentS)
append(HttpHeaders.Range, "bytes=${file.length()}-")
}
}
.execute { httpResponse ->
val channel: ByteReadChannel = httpResponse.receive()
while (!channel.isClosedForRead) {
val packet = channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong())
while (!packet.isEmpty) {
val bytes = packet.readBytes()
file.appendBytes(bytes)
println("Received ${(file.length())} bytes from ${httpResponse.contentLength()}")
}
}
val pathF = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/${fileName}")
file.renameTo(pathF)
println("A file saved to ${file.path}")
}
}
}
Can anyone help me solve this problem with ktor, if there is no solution, can someone tell me another way to achieve the same goal? Need to be with Kotlin.
update 2022-02-17
Thanks to Aleksei Tirman's help I managed to solve the problem, thank you very much. And the base code looks like this:
fun startDownload(url: String, auth: String = "", userAgentS: String = "", fileName: String = ""){
val client = HttpClient(CIO)
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val file = File.createTempFile("File", "index", path)
runBlocking {
client.get<HttpStatement>(url){
url {
parameters.urlEncodingOption = UrlEncodingOption.NO_ENCODING
}
headers {
append(HttpHeaders.Authorization, auth)
append(HttpHeaders.UserAgent, userAgentS)
append(HttpHeaders.Range, "bytes=${file.length()}-")
}
}
.execute { httpResponse ->
val channel: ByteReadChannel = httpResponse.receive()
while (!channel.isClosedForRead) {
val packet = channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong())
while (!packet.isEmpty) {
val bytes = packet.readBytes()
file.appendBytes(bytes)
println("Received ${(file.length())} bytes from ${httpResponse.contentLength()}")
}
}
val pathF = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/${fileName}")
file.renameTo(pathF)
println("A file saved to ${file.path}")
}
}
}
You can disable query parameters encoding by assigning the UrlEncodingOption.NO_ENCODING value to the urlEncodingOption property of the ParametersBuilder. Here is an example:
val requestBuilder = HttpRequestBuilder()
requestBuilder.url {
protocol = URLProtocol.HTTP
host = "httpbin.org"
path("get")
parameters.urlEncodingOption = UrlEncodingOption.NO_ENCODING
parameters.append("file", "/10/55/file.zip")
}
val response = client.get<String>(requestBuilder)

Android: HTTP request with Volley fails to call with parameters

I deployed a NLP model as an API with Flask. Now I want to call the API from my simple Android app to process some text and to return a prediction, however when the Android App performs the HTTP request using Volley it does not add the parameters in the URL for some reason. Here is the code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// button
val showButton = findViewById<Button>(R.id.showInput)
// text
val editText = findViewById<EditText>(R.id.editText)
// Setting On Click Listener
showButton.setOnClickListener {
// user input
val text = editText.text
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "http://192.168.100.12:5000/"
// Request a string response from the provided URL.
val request = object : StringRequest(Request.Method.POST,
url,
Response.Listener {
response ->
editText.setText(response.toString())
},
Response.ErrorListener { error ->
Log.i("error ", error.toString())
editText.setText("Volley error: $it ")
}) {
override fun getBodyContentType(): String {
return "application/json"
}
#Throws(AuthFailureError::class)
override fun getBody(): ByteArray {
val params = HashMap<String,String>()
params.put("text", text.toString())
return params.toString().toByteArray()
}
}
// Add the request to the RequestQueue.
queue.add(request)
// Showing the response
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
}
}
In essence, I am expecting the URL to be "http://192.168.100.12:5000/?text=<insert_text_here>", but the actual URL that the app calls is just "http://192.168.100.12:5000" without the parameters.
I know this because my Flask app returns this error:
AttributeError: 'NoneType' object has no attribute 'lower'
The error response code is 500.
I tested the Flask API with both the browser and Postman and it is working fine, but just in case I will leave the code here:
from flask import Flask,render_template,url_for,request,jsonify
from sklearn.externals import joblib
import traceback
app = Flask(__name__)
#app.route("/",methods=['GET','POST'])
def predict():
try:
tweet = request.args.get('text')
model = open('model.pkl','rb')
model = joblib.load(model)
prediction = model.predict([tweet])
if prediction == [0]:
return 'This tweet does not violate our Community Guidelines'
else:
return 'This tweet violates out Community Guidelines for hate speech'
except:
return traceback.format_exc()
if __name__ == '__main__':
app.run(host = '192.168.100.12',debug=True)
So far I also have tried the code from this post as well as using the GET method with getParams() function instead of getBody() as shown below, but none of them worked.
#Throws(AuthFailureError::class)
override fun getParams(): Map<String, String>? {
val params: HashMap<String, String> = HashMap()
params["text"] = text.toString()
return params
}
Can you please help me solve this issue? I would be very grateful.

I need help for post to my api. What should I do?

I'm creating a login for my application.
I am currently stuck in posting problems to my API
This is my API that which is made to support login.
{
success: false,
message: "Please provide complete and accurate information.",
data: [ ]
}
fun loginUrlSuccess(urlApi : String) {
Log.d("login", urlApi)
authSignin_cgi = gson.fromJson(urlApi, DtoProfile::class.java)
loginsSuccess = authSignin_cgi.success
val queue = Volley.newRequestQueue(context)
val stringReq = object : StringRequest(Request.Method.POST,urlApi,Response.Listener<String>{ response ->
Log.w("response",response)
Toast.makeText(context,"Loging success..",Toast.LENGTH_SHORT).show()
if (loginsSuccess){
Toast.makeText(context,authSignin_cgi.message,Toast.LENGTH_LONG).show()
} else {
Toast.makeText(context,authSignin_cgi.message,Toast.LENGTH_LONG).show()
}
},Response.ErrorListener { error ->
Log.w("error", error.toString())
Toast.makeText(context, "error..$error",Toast.LENGTH_SHORT).show()
}){
override fun getParams(): MutableMap<String, String> {
val param = HashMap<String, String>()
val userEmail = textEmail.text.toString().trim()
val userPassword = textPassword.text.toString().trim()
param["useremail"] = userEmail
param["userpassword"] = userPassword
return param
}
}
queue.add(stringReq)
}
I get an error from the Logcat screen.
So what do I have to do?
04-04 15:31:43.614 8365-8699/com.example.atimeonlin5 E/Volley: [700] NetworkDispatcher.processRequest: Unhandled exception java.lang.RuntimeException: Bad URL {"success":false,"message":"โปรดระบุข้อมูลให้ถูกต้องครบถ้วน","data":[]}
java.lang.RuntimeException: Bad URL {"success":false,"message":"โปรดระบุข้อมูลให้ถูกต้องครบถ้วน","data":[]}
All right , you should try to construct an Url object instead of type String !
You should use an url (like "http://www.google.com"), not a random string. Your urlApi is not url.
Example from doc:
val textView = findViewById<TextView>(R.id.text)
// ...
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "http://www.google.com"
// Request a string response from the provided URL.
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { textView.text = "That didn't work!" })
// Add the request to the RequestQueue.
queue.add(stringRequest)

Function in kotlin return value before ends Fuel.post

I have a function with Fuel.post that returns a value before Fuel.post ending, this is the code...
var res = rs.requestLogin("user", "password")
and my function
fun requestLogin(user : String, pass : String) : String {
var res = ""
val _params = HashMap<String, String>()
_params.put("user", user)
_params.put("pass", pass)
Fuel.post(Constantes.ENDPOINT_LOGIN, _params.toList())
.responseString(Charset.forName("UTF8")){ request, response, result ->
when (result) {
is Result.Success -> {
res = "0"
}
is Result.Failure ->{
res = "-1"
}
}
}
return res
}
I use this lib: https://github.com/kittinunf/Fuel
How i can return res value at Fuel.post ending?
Evidently you are using the async version of that call. By passing that lambda to responseString(), you are telling it you want that code to handle the response if and when it comes back at some point in the future, asynchronously.
I suspect if you use the blocking version, you might get the result you are after.
Totally untried code:
val (request, response, result) = Fuel.post(Constantes.ENDPOINT_LOGIN, _params.toList())
.responseString()
return if(result == Result.Success) "0" else "-1"

HTTP Request in Android with Kotlin

I want to do a login validation using POST method and to get some information using GET method.
I've URL, server Username and Password already of my previous project.
For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.
However, you can also use standard Java libraries like java.net.HttpURLConnection
which is part of the Java SDK:
fun sendGet() {
val url = URL("http://www.google.com/")
with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET" // optional default is GET
println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")
inputStream.bufferedReader().use {
it.lines().forEach { line ->
println(line)
}
}
}
}
Or simpler:
URL("https://google.com").readText()
Send HTTP POST/GET request with parameters using HttpURLConnection :
POST with Parameters:
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("<Your API Link>")
with(mURL.openConnection() as HttpURLConnection) {
// optional default is GET
requestMethod = "POST"
val wr = OutputStreamWriter(getOutputStream());
wr.write(reqParam);
wr.flush();
println("URL : $url")
println("Response Code : $responseCode")
BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
println("Response : $response")
}
}
}
GET with Parameters:
fun sendGetRequest(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("<Yout API Link>?"+reqParam)
with(mURL.openConnection() as HttpURLConnection) {
// optional default is GET
requestMethod = "GET"
println("URL : $url")
println("Response Code : $responseCode")
BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
it.close()
println("Response : $response")
}
}
}
Using only the standard library with minimal code!
thread {
val json = try {
URL(url).readText()
} catch (e: Exception) {
return#thread
}
runOnUiThread { displayOrWhatever(json) }
}
This starts a GET request on a new thread, leaving the UI thread to respond to user input. However, we can only modify UI elements from the main/UI thread, so we actually need a runOnUiThread block to show the result to our user. This enqueues our display code to be run on the UI thread soon.
The try/catch is there so your app won't crash if you make a request with your phone's internet off. Add your own error handling (e.g. showing a Toast) as you please.
.readText() is not part of the java.net.URL class but a Kotlin extension method, Kotlin "glues" this method onto URL. This is enough for plain GET requests, but for more control and POST requests you need something like the Fuel library.
Have a look at Fuel library, a sample GET request
"https://httpbin.org/get"
.httpGet()
.responseString { request, response, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
}
is Result.Success -> {
val data = result.get()
}
}
}
// You can also use Fuel.get("https://httpbin.org/get").responseString { ... }
// You can also use FuelManager.instance.get("...").responseString { ... }
A sample POST request
Fuel.post("https://httpbin.org/post")
.jsonBody("{ \"foo\" : \"bar\" }")
.also { println(it) }
.response { result -> }
Their documentation can be found here
​
I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.
val url = "https://example.com/endpoint"
val client = OkHttpClient()
val JSON = MediaType.get("application/json; charset=utf-8")
val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
val request = Request.Builder()
.addHeader("Authorization", "Bearer $token")
.url(url)
.post(body)
.build()
val response = client . newCall (request).execute()
println(response.request())
println(response.body()!!.string())
Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
UPDATE: July 7th, 2019
I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).
UPDATE: January 25th, 2021
Everything is okay with the most updated versions.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.12.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
Get Method
fun get() {
val client = OkHttpClient()
val url = URL("https://reqres.in/api/users?page=2")
val request = Request.Builder()
.url(url)
.get()
.build()
val response = client.newCall(request).execute()
val responseBody = response.body!!.string()
//Response
println("Response Body: " + responseBody)
//we could use jackson if we got a JSON
val mapperAll = ObjectMapper()
val objData = mapperAll.readTree(responseBody)
objData.get("data").forEachIndexed { index, jsonNode ->
println("$index $jsonNode")
}
}
POST Method
fun post() {
val client = OkHttpClient()
val url = URL("https://reqres.in/api/users")
//just a string
var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"
//or using jackson
val mapperAll = ObjectMapper()
val jacksonObj = mapperAll.createObjectNode()
jacksonObj.put("name", "Rolando")
jacksonObj.put("job", "Fakeador")
val jacksonString = jacksonObj.toString()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jacksonString.toRequestBody(mediaType)
val request = Request.Builder()
.url(url)
.post(body)
.build()
val response = client.newCall(request).execute()
val responseBody = response.body!!.string()
//Response
println("Response Body: " + responseBody)
//we could use jackson if we got a JSON
val objData = mapperAll.readTree(responseBody)
println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}
Maybe the simplest GET
For everybody stuck with NetworkOnMainThreadException for the other solutions: use AsyncTask or, even shorter, (yet still experimental) Coroutines:
launch {
val jsonStr = URL("url").readText()
}
If you need to test with plain http don't forget to add to your manifest:
android:usesCleartextTraffic="true"
For the experimental Coroutines you have to add to build.gradle as of 10/10/2018:
kotlin {
experimental {
coroutines 'enable'
}
}
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.24.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.24.0"
...
If you are using Kotlin, you might as well keep your code as succinct as possible. The run method turns the receiver into this and returns the value of the block.
this as HttpURLConnection creates a smart cast. bufferedReader().readText() avoids a bunch of boilerplate code.
return URL(url).run {
openConnection().run {
this as HttpURLConnection
inputStream.bufferedReader().readText()
}
}
You can also wrap this into an extension function.
fun URL.getText(): String {
return openConnection().run {
this as HttpURLConnection
inputStream.bufferedReader().readText()
}
}
And call it like this
return URL(url).getText()
Finally, if you are super lazy, you can extend the String class instead.
fun String.getUrlText(): String {
return URL(this).run {
openConnection().run {
this as HttpURLConnection
inputStream.bufferedReader().readText()
}
}
}
And call it like this
return "http://somewhere.com".getUrlText()
You can use kohttp library. It is a Kotlin DSL HTTP client. It supports the features of square.okhttp and provides a clear DSL for them. KoHttp async calls are powered by coroutines.
httpGet extension function
val response: Response = "https://google.com/search?q=iphone".httpGet()
you can also use async call with coroutines
val response: Deferred<Response> = "https://google.com/search?q=iphone".asyncHttpGet()
or DSL function for more complex requests
val response: Response = httpGet {
host = "google.com"
path = "/search"
param {
"q" to "iphone"
"safe" to "off"
}
}
You can find more details in docs
To get it with gradle use
implementation 'io.github.rybalkinsd:kohttp:0.12.0'
Without adding additional dependencies, this works. You don't need Volley for this. This works using the current version of Kotlin as of Dec 2018: Kotlin 1.3.10
If using Android Studio, you'll need to add this declaration in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You should manually declare imports here. The auto-import tool caused me many conflicts.:
import android.os.AsyncTask
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.net.URL
import java.net.URLEncoder
import javax.net.ssl.HttpsURLConnection
You can't perform network requests on a background thread. You must subclass AsyncTask.
To call the method:
NetworkTask().execute(requestURL, queryString)
Declaration:
private class NetworkTask : AsyncTask<String, Int, Long>() {
override fun doInBackground(vararg parts: String): Long? {
val requestURL = parts.first()
val queryString = parts.last()
// Set up request
val connection: HttpsURLConnection = URL(requestURL).openConnection() as HttpsURLConnection
// Default is GET so you must override this for post
connection.requestMethod = "POST"
// To send a post body, output must be true
connection.doOutput = true
// Create the stream
val outputStream: OutputStream = connection.outputStream
// Create a writer container to pass the output over the stream
val outputWriter = OutputStreamWriter(outputStream)
// Add the string to the writer container
outputWriter.write(queryString)
// Send the data
outputWriter.flush()
// Create an input stream to read the response
val inputStream = BufferedReader(InputStreamReader(connection.inputStream)).use {
// Container for input stream data
val response = StringBuffer()
var inputLine = it.readLine()
// Add each line to the response container
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
it.close()
// TODO: Add main thread callback to parse response
println(">>>> Response: $response")
}
connection.disconnect()
return 0
}
protected fun onProgressUpdate(vararg progress: Int) {
}
override fun onPostExecute(result: Long?) {
}
}
GET and POST using OkHttp
private const val CONNECT_TIMEOUT = 15L
private const val READ_TIMEOUT = 15L
private const val WRITE_TIMEOUT = 15L
private fun performPostOperation(urlString: String, jsonString: String, token: String): String? {
return try {
val client = OkHttpClient.Builder()
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.build()
val body = jsonString.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
val request = Request.Builder()
.url(URL(urlString))
.header("Authorization", token)
.post(body)
.build()
val response = client.newCall(request).execute()
response.body?.string()
}
catch (e: IOException) {
e.printStackTrace()
null
}
}
private fun performGetOperation(urlString: String, token: String): String? {
return try {
val client = OkHttpClient.Builder()
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.build()
val request = Request.Builder()
.url(URL(urlString))
.header("Authorization", token)
.get()
.build()
val response = client.newCall(request).execute()
response.body?.string()
}
catch (e: IOException) {
e.printStackTrace()
null
}
}
Object serialization and deserialization
#Throws(JsonProcessingException::class)
fun objectToJson(obj: Any): String {
return ObjectMapper().writeValueAsString(obj)
}
#Throws(IOException::class)
fun jsonToAgentObject(json: String?): MyObject? {
return if (json == null) { null } else {
ObjectMapper().readValue<MyObject>(json, MyObject::class.java)
}
}
Dependencies
Put the following lines in your gradle (app) file. Jackson is optional. You can use it for object serialization and deserialization.
implementation 'com.squareup.okhttp3:okhttp:4.3.1'
implementation 'com.fasterxml.jackson.core:jackson-core:2.9.8'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.9.8'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
You can use this library Fuel Library as well, which makes it further easier.
val map = mutableMapOf<String, String>()
map.put("id","629eeb9da9d8f50016e1af96")
val httpAsync = url
.httpPost()
.jsonBody(
Gson().toJson(map) // for json string
)
.responseString { request, response, result -> //do something with the response }

Categories

Resources