I'm calling python script using POST method and sending data in application/json format using Retrofit2
Python script accepts:
{
u'params': {
u'login': u'admin',
u'password': u'a',
u'db': u'hrm_v10',
u'base_location': u'10.42.0.149:8069'
},
u'jsonrpc': u'2.0',
u'id': 1,
u'method': u'call'
}
What I'm sending to server is:
{
"id": 1,
"jsonrpc": "2.0",
"method": "call",
"params": {
"base_location": "10.42.0.149:8069",
"db": "discuss_v10",
"login": "admin",
"password": "admin"
}
}
I want to know how to convert String to raw-data in Android.
Here's my code:
AuthenticateRequest.kt
interface AuthenticateRequest {
@Headers(
"Content-Type: application/json"
)
@POST("/web/session/authenticate")
fun authenticate(
@Body authenticateReqBody: String
): Call<Authenticate>
}
MainActivity.kt
val authenticateReq = app.retrofit.create(AuthenticateRequest::class.java)
val reqBody = AuthenticateReqBody(id = 1, params = Params(
App.host, App.login, App.password, App.database
))
val body = Gson().toJson(reqBody)
val call = authenticateReq.authenticate(body)
call.enqueue(object : Callback<Authenticate> {
override fun onFailure(call: Call<Authenticate>, t: Throwable) {
Log.d(TAG, "onFailure: " + t.message)
}
override fun onResponse(call: Call<Authenticate>, response: Response<Authenticate>) {
if (response.isSuccessful) {
Log.d(TAG, "onResponse: Success " + response.body())
} else {
Log.d(TAG, "onResponse: Failed " + response.errorBody()!!.string())
}
}
})
Thank you very much for your time and assistance in this matter.
If you are using GSON as convertor factory just use this
the object will be converted to json by default. no need of headers and String.