send request in data-form

Viewed 28

there is an API I'm working with it, and in login section API accepts only "data-form" request here is the solutions I found after many searches but it doesn't work

@Multipart
@POST("oauth/token")
suspend fun loginUser (@Part ("username") username:RequestBody,
                       @Part ("password") password:RequestBody,
                       @Part("grant_type") grantType:RequestBody):Response<Any>

and here is the instruction I took in MainActivity

val pass="password"
            lifecycleScope.launch {
               val request= movieService.loginUser(
                    username = userName.toRequestBody("text/plain".toMediaTypeOrNull()),
                    password = password.toRequestBody("text/plain".toMediaTypeOrNull()),
                    grantType = pass.toRequestBody("text/plain".toMediaTypeOrNull())
                )
                Log.i("login",request.body().toString())
            }
2 Answers

do not use from @Multipart.Multipart use from sending files to the server. Try to use from @FormUrlEncode.and use from @Field to send your data.

@FormUrlEncoded
@POST("oauth/token")
suspend fun loginUser (@Field("username") username:String,
                       @Field("password") password:String,
                       @Field("grant_type") grantType:String):Response<Any>

after many researches I find out this solution:

fragment instructure

val userNameBody :RequestBody= userName.toRequestBody()
            val passwordBody: RequestBody = password.toRequestBody()
            val grantTypeBody: RequestBody = "password".toRequestBody()



            viewModel.loginUser(userNameBody,passwordBody,grantTypeBody

Api service instructure

@Multipart
@POST("oauth/token")
suspend fun loginUser (@Part ("username") username:RequestBody,
                       @Part ("password") password:RequestBody,
                       @Part("grant_type") grantType:RequestBody
):Response<UserAuthModel>
Related