how to send rawdata to Python Script using Retrofit2

201 views Asked by At

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.

1

There are 1 answers

0
taman neupane On BEST ANSWER

If you are using GSON as convertor factory just use this

 @POST(Constants.URL.UPDATE_PROFILE_PIC)
    Call<ProfilePicUpdateHelper> updateProfilePic(@Body ProfilePicHelper profilePicHelper);

the object will be converted to json by default. no need of headers and String.