1

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 Answers2

0

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>
behrad
  • 1,228
  • 14
  • 21
  • I followed every instructure that has been mentioned in this post : https://stackoverflow.com/questions/37814857/retrofit-2-with-only-form-data however I have the same issue, but non of the solutions works for me – Farshad Molazeinali Jul 30 '22 at 10:07
0

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>