Search code examples
androidjsonpostmanretrofitform-data

How to do a post request using FORM-DATA or x-www-form-urlencoded with Android?


I have an issue with my code, I want to send a post with x-www-form-urlencoded or form-data, I need to send two parameters:

  • Email: String
  • Password: String

And after I receive two parameters in Json:

  • Token: String
  • Success: Boolean

It's important that the Email and Password are sent in Form-Data.

Postman example:

Postman example


Solution

  • Follow these steps to send Form data or URL encoded data in android using Retrofit.

    Build.gradle

    //Retrofit
    implementation "com.squareup.okhttp3:okhttp:3.8.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.8.0"
    implementation ("com.squareup.retrofit2:retrofit:2.5.0"){
    // exclude Retrofit’s OkHttp peer-dependency module and define your own module 
    import
    exclude module: 'okhttp'
    }
    

    Make interface class name

    ApiInterface.kt

    import retrofit2.Call
    import retrofit2.http.*
    interface ApiInterface {
    
    @FormUrlEncoded
    @POST("")
    fun register(
        @Field("email") email: String,
        @Field("password") password: String?,
    ): Call<EmailResponse>
    }
    

    MainActivity.kt

    val retrofit = Retrofit.Builder()
        .baseUrl(Constants.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    val service = retrofit.create(ApiInterface::class.java)
    val call = service.register(email, password)
    
    
    call!!.enqueue(object : Callback<EmailResponse> {
        override fun onResponse(
            call: Call<EmailResponse>,
            response: Response<EmailResponse>,
        ) {
            if (response.isSuccessful) {
    
                val emailResponse: EmailResponse = response.body()!!
                val token = emailResponse.token
                val success = emailResponse.success
    
            }
        }
    
        override fun onFailure(call: Call<EmailResponse>, t: Throwable) {
            Log.e(TAG, "onFailure: ")
        }
    })
    

    EmailResponse.kt

    data class EmailResponse(
    val token: String,
    val success: Boolean,
    )
    

    And you Constants.BASE_URL will be https://URLEJEMPLO.com